Re: Cocoa - Naive questions about memory
Re: Cocoa - Naive questions about memory
- Subject: Re: Cocoa - Naive questions about memory
- From: lbland <email@hidden>
- Date: Sun, 4 May 2003 18:22:27 -0400
On Sunday, May 4, 2003, at 05:22 PM, Danny Swarzman wrote:
- (void)setMainSprocket:(Sprocket *)newSprocket
{
[mainSprocket autorelease];
mainSprocket = [newSprocket retain]; /* Claim the new Sprocket. */
return;
}
Why is it necessary to call autorelease for he object to which
mainSprocket
pointed before setMainSprocket is
invoked. If there is another pointer to that object in another method,
won't that there be a call in that other method
to release the object using the other pointer. If there isn't another
pointer, by what mechanism could the memory
management system be able to dectect that the object is no longer used?
hi-
to answer one question...
- (void)setMainSprocket:(Sprocket *)newSprocket
{
[mainSprocket autorelease];
mainSprocket = [newSprocket retain]; /* Claim the new Sprocket. */
return;
}
the autorelease is probably a "style" of programming. If mainSprocket
== newSprocket && [mainSprocket release] && (mainSprocket not shared
elsewhere) then newSprocket is invalid and [newSprocket retain] will
bomb. to get around that [mainSprocket autorelease] is called so that
[mainSprocket release] is called after ([newSprocket retain]; /* Claim
the new Sprocket. */) the next time the autorelease pool in the scope
of the code is released.
I don't like that because it makes simple references global (increases
the scope of the reference). A better way IMHO is:
- (void)setMainSprocket:(Sprocket *)newSprocket
{
if(mainSprocket != newSprocket)
{
[mainSprocket release];
mainSprocket = [newSprocket retain]; /* Claim the new Sprocket. */
}
}
which keeps newSprocket out of the caller's autoreleasepool. this has
the added benefit of increasing the applicability of set* methods so
other related attributes can be invalidated, like this:
- (void)setMainSprocket:(Sprocket *)newSprocket
{
if(mainSprocket != newSprocket)
{
[mainSprocket release];
mainSprocket = [newSprocket retain]; /* Claim the new Sprocket. */
[self setNeedsDisplay:YES];
}
}
... but that has its own problems in that it un-diagonalizes (couples)
a matrix of attributes leading to explosion of methods.
-lance
Lance Bland
mailto:email@hidden
VVI
888-VVI-PLOT
http://www.vvi.com
_______________________________________________
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.