Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need release in the dealloc?

In the book I'm studying from for iPhone dev, they utilize IBOutlet instances using the Interface Builder. An example would be a UIButton. So they add a thing in the struct like this:

 IBOutlet UIButton *whateverButton;

Then they add a @property for each of these in the .h, and a @synthesize in the .m.

Then they include a release in the dealloc of the .m. Two questions:

  1. Is the release necessary? Aren't all properties already handled automatically?
  2. How can I check the ref count to see what's happening, for debug purposes...?
like image 982
Dan Rosenstark Avatar asked Apr 23 '26 11:04

Dan Rosenstark


1 Answers

Is the release necessary? Aren't all properties already handled automatically?

If the property is retained, the release is necessary. When you declare a @property and @synthesize it, all you get is the accessors, there is no special automatic behaviour in dealloc.

Also, there is nothing magical about IBOutlet – it’s just a marker for Interface Builder to see which properties you would like to appear in IB. It’s simply an empty macro, Cmd-click the IBOutlet keyword to see its definition:

#ifndef IBOutlet
#define IBOutlet
#endif

Same thing goes for IBAction which expands to void.

How can I check the ref count to see what's happening, for debug purposes...?

When I need to debug memory management, I usually simply set up a breakpoint in the dealloc method or log a string there. It is also helpful to log the retainCount of an object around the calls that might do something fishy with it.


It might also help to see how the @synthesize directive creates the accessors. When you declare a retained @property and ask the compiler to @synthesize them, you get something like this:

@property(retain) NSString *foo;
@synthesize foo;

- (void) foo {
    return foo;
}

- (void) setFoo: (NSString*) newFoo {
    // Try to think what would happen if this condition wasn’t
    // here and somebody called [anObject setFoo:anObject.foo].
    if (newFoo == foo)
        return;
    [foo release];
    foo = [newFoo retain];
}

This isn’t exactly the thing, but it’s close enough. Now it should be more clear why you should release in dealloc.

like image 130
zoul Avatar answered Apr 26 '26 04:04

zoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!