iPhone memory management (with specific examples/questions)

Posted by donkim on Stack Overflow See other posts from Stack Overflow or by donkim
Published on 2010-12-28T05:31:10Z Indexed on 2010/12/28 5:54 UTC
Read the original article Hit count: 214

Hey all. I know this question's been asked but I still don't have a clear picture of memory management in Objective-C. I feel like I have a pretty good grasp of it, but I'd still like some correct answers for the following code. I have a series of examples that I'd love for someone(s) to clarify.

  • Setting a value for an instance variable. Say I have an NSMutableArray variable. In my class, when I initialize it, do I need to call a retain on it?

Do I do

fooArray = [[[NSMutableArray alloc] init] retain];

or

fooArray = [[NSMutableArray alloc] init];

Does doing [[NSMutableArray alloc] init] already set the retain count to 1, so I wouldn't need to call retain on it? On the other hand, if I called a method that I know returns an autoreleased object, I would for sure have to call retain on it, right? Like so:

fooString = [[NSString stringWithFormat:@"%d items", someInt] retain];
  • Properties. I ask about the retain because I'm a bit confused about how @property's automatic setter works.

If I had set fooArray to be a @property with retain set, Objective-C will automatically create the following setter, right?

- (void)setFooArray:(NSMutableArray *)anArray {
    [fooArray release];
    fooArray = [anArray retain];
}

So, if I had code like this: self.fooArray = [[NSMutableArray alloc] init]; (which I believe is valid code), Objective-C creates a setter method that calls retain on the value assigned to fooArray. In this case, will the retain count actually be 2?

  • Correct way of setting a value of a property. I know there are questions on this and (possibly) debates, but which is the right way to set a @property?

This?

self.fooArray = [[NSMutableArray alloc] init];

Or this?

NSMutableArray *anArray = [[NSMutableArray alloc] init];
self.fooArray = anArray;
[anArray release];

I'd love to get some clarification on these examples. Thanks!

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c