views:

108

answers:

1

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?

+2  A: 

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.

Paul Tomblin
Thank you. That is all the explanation I needed.
jsumners
I disagree with your statement that it's “not good practice”. If an object holds a variable number of other objects, storing them in an array is a simple and obvious way to retain all of them.
Peter Hosey
Really it's better to set an example where you only release a variable after you've finished using it. The cycle should be obtain->use->discard, and relying on internal handling of things to validate obtain->discard->use-because-we-know-its-not-really-been-deleted-yet is kind of a bad idea, particularly when talking to people who are still learning the basic rules.
Jim Dovey
I agree with your comment Mr. Dovey. You have clearly outlined my source of confusion. But I also might not have been prompted to ask the question if the release came at the end of the function. Maybe this book is assuming a little too much familiarity with Objective-C.
jsumners
It's definitely not "assuming a little too much familiarity with Objective-C" as reference counting is a Cocoa feature. If the reader doesn't understand how placing an object into an array will retain it, they are clearly too far into the book for their current skill level and should backtrack to the memory management sections again.
Mike Abdullah
Reference counting is not an Cocoa feature, it is an Objective-C feature. Cocoa is a framework, a grouping of libraries compiled using an objective-c compiler.
Evan
Reference counting is a feature of the Cocoa framework. Objective-C does not come with any reference-counting functionality out of the box. The Object root class's only memory management methods are alloc and free. It's NSObject that implements the retain/release system.
Chuck