Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Specific, General Objective-C Memory Management

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];

like image 474
SooDesuNe Avatar asked Mar 13 '26 12:03

SooDesuNe


1 Answers

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:

  1. releasing foo
  2. retaining bar
  3. assigning foo to bar

The assignments foo = bar and foo = [bar retain] don't release the previous object of foo.

like image 105
notnoop Avatar answered Mar 15 '26 02:03

notnoop



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!