Re: Accessor methods and (auto)release: conclusion
Re: Accessor methods and (auto)release: conclusion
- Subject: Re: Accessor methods and (auto)release: conclusion
- From: Marco Scheurer <email@hidden>
- Date: Tue, 6 Aug 2002 18:47:56 +0200
On Tuesday, August 6, 2002, at 05:38 pm, Shawn Erickson wrote:
Again true... you don't need to use it (in some case it is overkill and
can be a performance issue) but if others may use your class and it
doesn't follow the expected pattern then PLEASE document that it does
NOT do so.
First, it is not just a performance issue. To me, it has more to do with
complexity, ease of debugging, and program correctness than performance.
Second, since when is this the expected pattern and where is it
documented? AFAIK, it has only been discussed in this mailing list. I'm
pretty sure that the vast majority of Cocoa classes do not use this
pattern (rightly so), and do not and should not document that they
don't. In fact, the opposite can be found in Apple's documentation:
file:///Developer/Documentation/Cocoa/TasksAndConcepts/ProgrammingTopics/MemoryMgmt/
index.html
For example, if you ask for an object's main sprocket and then release
the object, you have to consider the main sprocket gone, because it
belonged to the object. Similarly, if you ask for the main sprocket and
then send setMainSprocket: you cannot assume that the sprocket you
received remains valid:
Sprocket *newMainSprocket;
Sprocket *oldMainSprocket;
oldMainSprocket = [myObject mainSprocket];
/* If this releases the original Sprocket... */
[myObject setMainSprocket:newMainSprocket];
/* ...then this causes the application to crash. */
[oldMainSprocket anyMessage];
setMainSprocket: may release the object's original main sprocket,
possibly rendering it invalid. Sending any message to the invalid
sprocket would then cause your application to crash. If you need to use
an object after disposing of its owner or rendering it invalid by some
other means, you can retain and autorelease it before sending the
message that would invalidate it:
Sprocket *oldMainSprocket;
Sprocket *newMainSprocket;
oldMainSprocket = [[[myObject mainSprocket] retain] autorelease];
[myObject setMainSprocket:newMainSprocket];
[oldMainSprocket anyMessage];
Retaining and autoreleasing oldMainSprocket guarantees that it remains
valid throughout your scope, even though its owner may release it when
you send setMainSprocket:.
This is Ondra's "ugly" pattern.
Marco Scheurer
Sen:te, Lausanne, Switzerland
http://www.sente.ch
_______________________________________________
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.