I am going through Cocoa Programming for Mac OS X by Aaron Hillegrass and have come to something I do not understand. On page 150-151 he creates an object, releases it, and then uses it again. For example:
- (void) someMethod
{
NSMutableArray *array = [[NSMutableArray alloc] init];
NSString *str = [[NSString alloc] initWithString:"This is a string."];
[array addObject:str];
[str release];
int x = [array indexOfObjectIdenticalTo:str];
NSLog(@"the index of %@ in the array is %d", str, x);
}
How does this work if the object has been released? Is the object still valid until the method is finished or set to nil?
Adding it to the array will increase the reference count, so the explicit release will leave the reference count as 1. It’s not good practice (you shouldn’t release something until you’re done referencing it), but in this case it’s safe.