Search code examples
iphoneiosrelease-management

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?

(Line 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


Solution

  • There are few points we should discuss.

    1. 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.
    2. 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.
    3. 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.