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: Shaun Wexler <email@hidden>
- Date: Wed, 22 Sep 2004 11:36:33 -0700
On Sep 22, 2004, at 11:16 AM, James Bucanek wrote:
BufferPool lives in thread "bp_thread". BufferPool is a factory
object which creates Buffer objects in response to [BufferPool
bufferFromPool].
As per the Cocoa guidelines, BufferPool was doing this via 'return
[[[Buffer alloc] initWithSomeMagic] autorelease]' so the returned
object was autoreleased (in bp_thread's pool).
The Buffer is then immediately placed in a queue of "ready to use"
buffers.
Clients (running in other threads) then pull Buffers out of the queue,
work on them, then push them onto an "all done" queue.
The consumer of the "all done" queue is the orignal bp_thread, which
assembles the Buffers and write them to disk. At this point bp_thread
would like to immediatley release the Buffer so it can be recycled.
The problem was that because BufferPool autoreleased the Buffer in the
first place it can't be released immediately.
The point that mmalc was trying to make was that you include two
methods in your Buffer abstract class, one named +bufferFromPool which
provides autoreleased instances, and one named +newBufferFromPool which
provides instances with retainCount = 1, regardless if the buffer was
allocated or already existed. This is consistent with Apple's ObjC
naming conventions.
Adding an object to an NSAutoreleasePool is not a cheap operation. If
you're going to immediately place the object into a retaining queue, it
should be:
id buffer;
if ((buffer = [Buffer newBufferFromPool])) {
[queue enqueueBuffer:buffer];
[queueSemaphore signal];
// [buffer release];
}
This way, pulling the object from the queue will not need to be wrapped
with retain/release again. When an object is pulled, the "puller"
gains ownership. When it is done with the buffer, it must be released,
unless it is being handed off to a new queue/owner.
BTW, your Buffer class should maintain a hashtable of its objects,
especially if it's not creating/destroying them at a high rate. I have
a base class which does exactly this.
My only problem is all the special cases where there is an error and
the Buffer is not completely processed for some reason. I'll have to
take care of sending an extra release to the objects that dont' make
it back to the original thread, rather being able to rely on the
autorelease pool to do it for me. *sigh*
Add an owner property to each Buffer?
- (void)disposeBuffer
{
bufferOwner = nil;
[self release];
}
--
Shaun Wexler
MacFOH
http://www.macfoh.com
_______________________________________________
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