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?
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:
This will ensure your
if (!varArray)check will be correct.