1

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 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

It's generally considered fine to bypass the accessor in the init method.
1

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

self.myArray = [NSMutableArray array];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.