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
There are few points we should discuss.
releasedoes 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.NSMutableArraywill 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
retainthe reference when added, so the reference will not be deallocated yet after releasingdateAttribute. However, this is not a good style because its validity depends solely on the nature of the classNSMutableArrayitself, and it breaks common rule that we should not use released reference.