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开发者_StackOverflow中文版 policy
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).
Your code is all right and doesn't leak. But it seems like you don’t really understand pointers. A pointer can not own another object, it is just a reference that tells the computer which object is being accessed. In the reference-counted memory model of Cocoa it doesn’t matter at all how many pointers point to a single object.
You really should learn C (especially about pointers) before you try to learn Objective-C.
Your example will not result in a memory leak as var1
and var2
point to the same object in memory—thus the alloc
call has a matching release
. If the NSObject
was retained as it was assigned to var2
however, there would be a memory leak as there would be no matching release
.
When the memory management guide talks about the concept of ownership, it doesn't mean that a variable (e.g. var1
) owns an object; it's more about what "scope" owns it (e.g. a class or method). In your example, the method containing those statements would be responsible for releasing the object.
It's the object that keeps a reference count, not the pointer to the object. If you have a dozen pointers to an object, you could use any one of them to release the object because they're all pointing to the same object. However, it's a lot easier to follow your code and make sure that you don't have memory management problems if you don't play those sorts of games.
精彩评论