Search code examples
objective-cmemorymemory-managementretaincount

Can we release some memory in Objective-c that a variable does not own but points to?


I have some code like this:

NSObject *var1 = [[NSObject alloc] init];
NSObject *var2 = var1;
[var2 release]; 

var1 = nil;

Is this correct or is this a memory leak? As far as I know only var1 can release the memory alloc-inited in the first line, as per the Object Ownership policy


Solution

  • Your code will release the memory, because there is a single alloc, and a single release - the amount of pointers to the object is not a factor.

    Ownership is a concept that the Object Ownership policy talks about because if you follow the guidelines it makes it easier to manage and ultimately prevent problems relating to releasing things you shouldn't release (or not releasing things you should).