Jonathan.
Jonathan.

Reputation: 55604

iphone memory management: alloc and retain properties

According to the docs, you do one release per alloc or retain (etc) However what about when using retain propertys?

eg:

HEADER
@property(retain)UIView *someView;

IMPLEMENTATION
/*in some method*/
UIView *tempView = [[UIView alloc] init]; //<<<<<ALLOC - retain count = +1
[tempView setBackgroundColor:[UIColor redColor]];
self.someView = tempView; ///<<<<<RETAIN - retain count = +2
[tempView release];   ///should I do this?

or a different version of the IMPLEMENTATION

self.someView = [[UIView alloc] init]; //<<<<<ALLOC & RETAIN - retain count = +2
//now what??? [self.someView release]; ????

EDIT: I didn't make it clear, but I meant what to do in both circumstances, not just the first.

Upvotes: 0

Views: 271

Answers (3)

Hejazi
Hejazi

Reputation: 17015

For the second sample, you can use autorelease:

self.someView = [[[UIView alloc] init] autorelease];

Upvotes: 0

grahamparks
grahamparks

Reputation: 16296

Your first version is correct. There's only one ongoing reference to the view, so a retain count of 1 is appropriate.

Upvotes: 0

fsaint
fsaint

Reputation: 8759

/*in some method*/
UIView *tempView = [[UIView alloc] init]; //<<<<<ALLOC - retain count = +1
[tempView setBackgroundColor:[UIColor redColor]];
self.someView = tempView; ///<<<<<RETAIN - retain count = +2
[tempView release];   ///should I do this? // YES!!!!

And you should also release all retain properties in your dealloc method, before [super dealloc].

Upvotes: 3

Related Questions