PATH Documentation > Cocoa

PreviousNext 

Marking Objects for Disposal

The autorelease method, defined by NSObject, marks the receiver for later release. By autoreleasing an object-that is, by sending it an autorelease message-you declare that you don't need the object to exist beyond the scope you sent autorelease in. When your code completely finishes executing and control returns to the application object (that is, at the end of the event loop), the application object releases the object. The sprockets method above could be implemented in this way:

- (NSArray *)sprockets
{
    NSArray *array;

    array = [[NSArray alloc] initWithObjects:mainSprocket,
                               auxiliarySprocket, nil];
    return [array autorelease];
}

When another method gets the array of Sprockets, that method can assume that the array will be disposed of when it's no longer needed, but can still be safely used anywhere within its scope (with certain exceptions; see "Validity of Shared Objects" ). It can even return the array to its invoker, since the application object defines the bottom of the call stack for your code. The autorelease method thus allows every object to use other objects without worrying about disposing of them.


Note: Just as it's an error to release an object after it's already been deallocated, it's an error to send so many autorelease messages that the object would later be released after it had already been deallocated. You should send release or autorelease to an object only as many times as are allowed by its creation (one) plus the number of retain messages you have sent it (retain messages are described below).



PreviousNext 

© 2001 Apple Computer, Inc.





Site Map |  Search Tips |  Options |  Keywords

Contact Us | Privacy Notice
Copyright © 2000 Apple Computer, Inc. All rights reserved.
1-800-MY-APPLE