views:

84

answers:

3

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] and then ending up with a retain count of 2 for that object, but only releasing once in the dealloc. 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.

UPDATE

I actually found the answers (and even more details) here in case anyone is interested in reading more.

+3  A: 

self.myArray = is exactly the same as [self setMyArray:...].

You could however do myArray = [[NSMutableArray alloc] init]; which would end up with a retain count of 1 and would be totally legit.

Joonas Trussmann
+1  A: 

Yes, self.myArray = ... is the same as [self setMyArray:...]

So the set process adds a redundant retain to your object. You should probably release it immediately after the set, although I have seen some code that uses autorelease, one way or another. Both approaches are awkward.

Avoiding the set accessor (myArray = ...) is possible, but bypassing accessors is also frowned on by purists.

Paul Lynch
It's generally considered fine to bypass the accessor in the init method.
JeremyP
+1  A: 

Another option is to use the convenience methods returning autoreleased instances:

self.myArray = [NSMutableArray array];
sbooth