Use the object after it's released?

I am going through Cocoa Programming for Mac OS X by Aaron Hillegrass and came up with something that I don't understand. On page 150-151, it creates the object, frees it, and then uses it again. For instance:

- (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 it work if the object has been released? Is the object valid until the method completes or is set to nil

?

0


a source to share


1 answer


Adding it to the array will increase the reference count, so an explicit release will leave the reference count at 1. It's not a good practice (you shouldn't release anything until you're done referencing it), but in this case it's safe.



+2


a source







All Articles