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…
Assigning
nilto tmpArray only sets your pointer to the object tonil. It does not affect the object itself (or its lifecycle) at all. In this case, setting the objects you’ve created tonildoes nothing, since their variable declaration is in local scope – if you want the objects to be deallocated from memory you need to send themreleasebefore setting the pointer to the object tonil.However, sending
removeAllObjectsis 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:You won’t need to use
removeAllObjectsin the above case because it will be autorelease’d. I suggest you read this.