Everything i've read about objective-c memory management makes it sound incredible easy. To paraphrase everyone: "release whatever you alloc, retain or copy". But I think there are some more specific cases that are not so clear cut. Below are some sample situations. What is the correct procedure for each:
SITUATION #1:
Foo *foo = [[foo alloc] init];
Foo *fooToo = [[[foo alloc] init] autorelease];
foo = fooToo;
does foo need to be released before it is assigned to fooToo?
SITUATION #2 I seem to get a lot of crashes when I do things like: (.h and .m mashed together for convenience)
Foo *foo;
@property (nonatomic, retain) Foo *foo;
@synthesize foo;
-(id)init{
self = [super init];
}
-(void)dealloc{
[super dealloc];
[foo release];
}
I'm constantly told "always release in dealloc what you set a retain property for". But this will crash, if done like I've shown.
SITUATION #3 A similar situation that will also crash: (.h and .m mashed together for convenience)
Foo *foo;
@property (nonatomic, retain) Foo *foo;
@synthesize foo;
-(id)init{
self = [super init];
self.foo = nil;
}
-(void)dealloc{
[super dealloc];
[foo release];
}
for some reason when my code makes it down to dealloc, foo isn't == nil.
SITUATION #4 Finally, just a question, what general thought process do people use when deciding between
self.foo = bar;
and
foo = bar;
when foo is declared the same as in the above cases? Is self.foo just another way of coding:
foo = [bar retain];
Situation #1:
Yes, you do need to release foo before you lose your reference to it. Given that you allocated it, you are responsible for releasing it. If you re-assign foo before releasing it, you cannot release it anymore!
Situation #2:
The proper implementation of dealloc is:
- (void)dealloc {
[foo release];
[super dealloc];
}
The dealloc method needs to call the super's dealloc method not the release method. Also, you need release the fields first before calling [super dealloc]
Situation #3: Same as situation #2.
Situation #4:
I always prefer using self.foo = bar, as it does the following steps automatically, if needed:
foobarfoo to barThe assignments foo = bar and foo = [bar retain] don't release the previous object of foo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With