Sam
Sam

Reputation: 829

NSMutableArrays - can I do this?

In my app, the singleton class (SharedData) allocates memory for a NSMutableArray:

[self sharedMutableArray] = [[NSMutableArray alloc] init];

Class A populates the this sharedMutableArray:

NSObject *obj = [NSObject alloc] init];
[sharedMutableArray  addObject];
obj = nil;

Class B does this - and that's my question:

NSMutableArray *tmpArray = sharedMutableArray;
       ... uses the tmpArray locally
[tmpArray removeAllObjects];
tmpArray = nil;

This is an inherited code and my hunch is that this is a NO-NO. Can some one confirm that assigning nil to tmpArray will release memory for sharedMutableArray also.... I guess the author wanted to release tmpArray only...

Upvotes: 0

Views: 109

Answers (2)

Caleb
Caleb

Reputation: 125037

tmpArray is a pointer, and it's initialized to point to the same mutable array that sharedMutableArray points to. For that reason, the line:

[tmpArray removeAllObjects];

will empty out the array, and anyone using sharedMutableArray will see that change. In other words, the assignment

NSMutableArray *tmpArray = sharedMutableArray;

doesn't make a copy of the array itself, it only copies the pointer. Any messages you send using that pointer will go to the shared array. Likewise, assigning nil to tmpArray sets the pointer tmpArray, but doesn't do anything to the array itself.

Finally, setting a variable to nil never releases memory. Setting a property to nil, on the other hand, will release memory under some conditions (e.g. when the property is declared to retain its contents). You're setting a variable here, not a property, so there's no chance that the array will be released.

Upvotes: 0

Alan Zeino
Alan Zeino

Reputation: 4396

Assigning nil to tmpArray only sets your pointer to the object to nil. It does not affect the object itself (or its lifecycle) at all. In this case, setting the objects you've created to nil does nothing, since their variable declaration is in local scope - if you want the objects to be deallocated from memory you need to send them release before setting the pointer to the object to nil.

However, sending removeAllObjects is affecting your original sharedArray, because you didn't copy the array, you simply set a new pointer to point to the 'singleton'. You probably want this:

NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:sharedMutableArray];

You won't need to use removeAllObjects in the above case because it will be autorelease'd. I suggest you read this.

Upvotes: 1

Related Questions