Objective-C: alloc of object within init of another object (memory management)

Posted by Stefan Klumpp on Stack Overflow See other posts from Stack Overflow or by Stefan Klumpp
Published on 2010-05-12T11:19:43Z Indexed on 2010/05/12 11:24 UTC
Read the original article Hit count: 194

In my .h file I have:

NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableArray *myArray;

My .m file looks basically like this:

@synthesize myArray;

- (id) init {
    self = [super init];

    if (self != nil)
    {
        self.myArray = .... ? // here I want to create an empty array
    }

    return self;
}

- (void) dealloc {
    [self.myArray release];

    [super dealloc];
}

What I'm not sure about is what do to in the init.

1)

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

2)

NSMutableArray *tmp = [[NSMutableArray alloc] init];
self.myArray = tmp;
[tmp release];

Solution 1 doesn't seem right to me, because of my @property (retain) setting I automatically increase the retain counter when setting self.myArray, but additionally I have already a "+1 retain" due to the [NSMutableArray alloc]. Thus the second solution seems more correct to me, even though it is cumbersome.

Also am I wondering if self.myArray = ... is actually the same as [self setMyArray:...] and thus does increase the retain count.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about memory-management