Re: Accessor methods and (auto)release <Memory trail>
Re: Accessor methods and (auto)release <Memory trail>
- Subject: Re: Accessor methods and (auto)release <Memory trail>
- From: Ali Ozer <email@hidden>
- Date: Wed, 31 Jul 2002 10:27:11 -0700
So, to flesh out your example, you are concerned about this kind of
code:
{
str = [someObj title];
if (someCondition)
[someObj setTitle:@"foo"];
NSLog (@"The string is %@", str];
}
If so, it seems to me that the proper technique is to substitute
str = [[[someObj title] retain] autorelease];
for the first line of code.
I am concerned about the more subtle case such as:
str = [myWindow title];
...
[myDocument saveDocument];
...
... use str ...
Assuming myDocument is the document in myWindow, a side effect of the
"saveDocument" call might be to release the title you got back in the
first line. A retain/autoreleased return from the first line would
eliminate this potential issue, which could be hard to debug.
It's also possible to build an example here of why Method 1 (setter
does autorelease) could be bad in this situation. Consider, if
saveDocument was implemented as:
pool = [[NSAutoreleasePool alloc] init];
...
if (isUntitled) {
...put up save panel, get new name...
[myWindow setRepresentedFilename:newDocumentFileName];
}
...
[pool release];
I am assuming here that setRepresentedFilename: ends up changing the
title of the window. In this case, due to the nested autorelease pool,
even if the setTitle: method did an autorelease, the value will still
be released when "str" is accessed in the outer function.
Method 2, where you do retain/autorelease in the getter, ends up being
safer. In cases where performance isn't critical ([window title] is not
likely to be called thousands of times a second), I believe it's a good
idea to go the safer route to reduce surprise for clients.
Of course there are exceptions, such as the Foundation collection
classes as Ondra pointed out in an email to me. There, the collections
are just that --- low-level containers that hold your objects --- and
we don't want them autoreleasing or otherwise changing the lifetimes of
your objects, and of course performance is a major consideration. So
there, setObject:forKey:, removeObject:, etc are all very explicit,
without any autoreleasing.
Ali
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.