Re: Which class methods return autoreleased objects?
Re: Which class methods return autoreleased objects?
- Subject: Re: Which class methods return autoreleased objects?
- From: Gwynne <email@hidden>
- Date: Mon, 6 Dec 2004 18:59:45 -0500
On Dec 6, 2004, at 6:16 PM, Ricky Sharp wrote:
Where in the documentation do you find out, whether or not a class
method returns an autoreleased object?
[snip]
So how do you determine when a class method returns an autoreleased
object?
As the docs[1] mention, you basically just assume that they do. I
don't think you'll find any explicit documentation on the individual
APIs stating that assumption.
Also remember that when writing your own class methods that create
instances, they too should always return them autoreleased. This will
follow the proper pattern so that all objects can play nicely
together.
That's the long answer :). The short answer is that if a method doesn't
have "init" or "copy" in its name, it returns an object you shouldn't
release unless you retain it first.
This USUALLY translates to autoreleased, but there are some instances
in which it doesn't. [NSFileManager defaultManager] comes to mind. That
object is (probably) not autoreleased, but you shouldn't release it
yourself either. On the other hand, it's probably a safe bet that
[NSString stringWithFormat:] returns an autoreleased string.
You should treat both cases the same way: unless you put your own
retain on the object, it is only valid in the autorelease scope in
which you received it. Autorelease scope is never larger than function
scope, though it can be smaller if you create your own autorelease pool
inside a function. Here are some examples:
- (void)someMethod
{
NSString *someString = [NSString stringWithString:@"test"];
} // someString MUST be considered invalid now
- (void)anotherMethod
{
someIVar = [[NSString stringWithString:@"test it again!"] retain];
// very important to put the retain on it!
} // someIVar is still valid, but only because of the retain
- (void)stillMoreMethods
{
NSString *theFirstString = [NSString stringWithString:@"blah blah
blah"];
NSString *youGottaLoveTheseStrings;
// do some work here
{
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
youGottaLoveTheseStrings = [NSString stringWithString:@"tired yet?"];
// the variable is valid here
// do some work that does a lot of autoreleasing, a good reason for
// creating your own autorelease pool
[innerPool release]; // youGottaLoveTheseStrings is now invalid!!
}
// do some other work here; theFirstString is still valid
} // theFirstString is now invalid
-- Gwynne, key to the Code
Email: email@hidden
Web: http://musicimage.plasticchicken.com/
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden