Releasing an object but still able to use it
I had understood that once you release an object, you shouldn't use it as it will cause an error since it is not in memory anymore.
But reading thru this Apple guide, I found this code, and have also seen it before, but I would just move the [object release]
to the end of my code, so as to avoid getting an error. But it seems that it is accepted and works. So, why does this work? How can it keep setting variables to dateAttribute
after it's been released?
(Li开发者_JS百科ne 3 is the one in question):
NSMutableArray *runProperties = [NSMutableArray array];
NSAttributeDescription *dateAttribute = [[NSAttributeDescription alloc] init];
[runProperties addObject:dateAttribute];
[dateAttribute release];
[dateAttribute setName:@"date"];
[dateAttribute setAttributeType:NSDateAttributeType];
[dateAttribute setOptional:NO];
Got it from here: Creating a managed object model in code
There are few points we should discuss.
release
does not always make the object deallocated. The object will be deallocated only at the "last" release, i.e. when the retain count drop to zero.- Despite of that, it is still hold true that you should not use the object after you release it, because it is possible that it might be deallocated already.
- The
NSMutableArray
will retain the object until it is removed from the array, or the array itself be allocated.
The example take the advantage that the array will retain
the reference when added, so the reference will not be deallocated yet after releasing dateAttribute
. However, this is not a good style because its validity depends solely on the nature of the class NSMutableArray
itself, and it breaks common rule that we should not use released reference.
Technically, this is bad style, however it does work.
NSMutableArray (the runProperties addObject) calls retain
on the dateAttribute. Therefore, calling release does not destroy the dateAttribute (there is still one reference).
For readability and refactoring reasons, I would also place the call to release
last.
精彩评论