Re: Newbie question: how to release an object that has been autoreleased
Re: Newbie question: how to release an object that has been autoreleased
- Subject: Re: Newbie question: how to release an object that has been autoreleased
- From: Glenn Andreas <email@hidden>
- Date: Wed, 22 Sep 2004 14:17:25 -0500
At 8:03 AM -0700 9/22/04, James Bucanek wrote:
Ondra Cada wrote on Wednesday, September 22, 2004:
Uh, sorry, but I beg to differ: IMHO, the following pattern is not that
good.
On 22.9.2004, at 9:29, mmalcolm crawford wrote:
Buffer *bufferFromPool = [Buffer newBufferFromPool];
// ...
[bufferFromPool release];
? No autorelease "issues," and more efficient.
Also considerably more prone to programmer's errors of the new/release
mismatch kind, which is pretty bad. And also prone to leak if an
exception is raised.
Here's another good reason why this won't work: I can't call the
Buffer constructor directly.
The message that creates the Buffer object is a factory method,
which creates any of several sub-classes of Buffer depending on the
type of the pool. The type information, and the variables needed to
initialize the Buffer object, are private to the Pool object. To
allow the client to create the Buffer objects directly would destroy
my encapsulation.
This isn't all that different than the way a class cluster is
designed, and works because "init" can return something other than
"self". Thus there isn't a need to have a factory method to decide
what to do - this logic can be pushed into the init method itself.
For example, [NSArray array] and [[[NSArray alloc] init] autorelease]
can do the exact same thing (such as making a NSCFArray with the
mutability flag set to false).
This avoids the problem with "to create the Buffer objects directly
would destroy encapsulation" since even though it "looks" like the
user is creating a buffer object, they are actually creating a
subclass (but they don't know it yet). This is the same as a class
cluster.
By doing this, you avoid the "newBufferNotAutoreleased" method - if
you don't want to create an autoreleased object, [[Buffer alloc]
init] will work just fine.
Never overlook the ability to return something other than self from
init - its a very powerful technique (you can also use this to
guarentee that there is only one instance of a given class, for
example, which makes it easy to have a singleton that the user can
"override").
--
Glenn Andreas email@hidden
<http://www.gandreas.com/> oh my!
Mad, Bad, and Dangerous to Know
_______________________________________________
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