Re: I think I get it
Re: I think I get it
- Subject: Re: I think I get it
- From: "M. Uli Kusterer" <email@hidden>
- Date: Mon, 5 May 2003 14:53:34 +0200
A program may call retain many times. A programmer must make sure that for
an object the number of calls to retain is greater than or equal to the
number of calls to retain plus one. The plus one is because when memory is
first allocated for an object, the retain count is one.
I think one of the "retain"s above should be a "release". But note
that the actual formula is:
(# of retains +1) == (# of releases)
If you release less, you have a memory leak. If you release more,
you'll crash, because when you make the first additional call to
release, you're sending a message to an object that has already been
de-allocated. And while you can send a message to NIL without ill
effect (nothing will happen whatsoever), you can't send a message to
an object that's already been destroyed.
When the number of calls to release reaches the number of calls to retain
plus one for an object, the memory allocated to the object is released.
Yes. Since you say that, I guess you already knew what I wrote
above... I'll leave it in nonetheless.
Equivalent to invoking autorelease in C would be to call release at the end
of A for the object. That is if you assume that A is at the top level of
the methods invoked in the event loop. Invoking autorelease in C avoids
clutter and makes the program easier to write.
Yes :-) Wonderfully phrased!
Using a factory method avoids the need to call autorelease. The example on
the stepwise site says these are equivalent:
alertString=[NSMutableString stringWithString:@"The following error occured"]
alertString=[[[NSMutableString alloc] initWithString:@"The following error
occured"] autorelease];
Both create an object whose life cycle is from the execution of the
statement to the cleanup done on the autorelease pool at the next cycle of
the event loop.
Yes. It may help to simply think of factory methods as automatically
calling autorelease after they have created the object (which, for
all I know, is what they do). I.e. stringWithString is probably
implemented internally as:
+(id) stringWithString: (NSString*)str
{
NSString* theStr = [[NSString alloc] initWithString:str];
[theStr autorelease];
return theStr;
}
As the cofounder of Next, Ross Perot, would say "It's that simple."
Yes. Cool, isn't it? And to think I used to have to re-engineer such
things for ages until I finally got a good book on Cocoa ...!
--
Cheers,
M. Uli Kusterer
------------------------------------------------------------
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de
_______________________________________________
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.