Anna Fortuna
Anna Fortuna

Reputation: 1071

Proper way of initializing NSMutableArray

I have an ivar which is a NSMutableArray. I've seen some people use this function as a way to initialize an array:

- (NSMutableArray *)varArray
{
   if (!varArray)
      varArray = [[NSMutableArray alloc]init];

   return varArray;
}

And the array is released in dealloc.

When I tried to do this, sometimes the array is initialized, sometimes not.

So what I'm asking is, Is this a good way to initialize an ivar NSMutableArray, or is it better to do this: varArray = [[[NSMutableArray alloc]init]autorelease]; instead?

Upvotes: 2

Views: 2841

Answers (2)

justin
justin

Reputation: 104718

So what I'm asking is, Is this a good way to initialize an ivar NSMutableArray

No.

Simply implement your object's designated initializer and initialize the array there:

- (id)init
{
  self = [super init];
  if (0 == self)
    return 0;
  varArray = [NSMutableArray new];
  return self;
}

Upvotes: 0

Stunner
Stunner

Reputation: 12224

Doing this line:

varArray = [[NSMutableArray alloc]init];

Is always fine, but in which function is where it matters. It appears you are initializing it in the variable's setter, so whenever you query for that instance variable it should always exist... in theory. But issues may occur if you merely dealloc the ivar without setting it to nil so the following will explicitly reset the ivar pointer so that it is guaranteed to be nil when dealloced:

[varArray dealloc];
varArray = nil;

This will ensure your if (!varArray) check will be correct.

Upvotes: 1

Related Questions