Re: async NSOperation and NSOperationQueue
Re: async NSOperation and NSOperationQueue
- Subject: Re: async NSOperation and NSOperationQueue
- From: Jason Coco <email@hidden>
- Date: Mon, 15 Sep 2008 13:31:54 -0400
On Sep 15, 2008, at 11:02 , John Love wrote:
I must be doing something terribly wrong, because when I start up
the NSOperationQueue that does some time consuming calculations, I
do not get back control of my application until after the lengthy
calculation is complete. Here are the relevant code snippets:
- (void) calculateWorksheetRow:(id)data {
// takes a long time here
}
- (void) startQueue {
theQueue = [[[NSOperationQueue alloc] init] autorelease];
theOp = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(calculateWorksheetRow:)
object:nil];
[theQueue addOperation:theOp];
}
Couple of things... you don't wanna create a queue every time. You
should
pretty much have just one queue that you add NSOperation objects to. You
probably want to re-write this to be a singleton object that you get
from your
app controller or some other relevant place.
Also, you most definitely do not want to autorelease your queue. It
will end
up going away on you when you least want it to or expect it to. Create
your
queue somewhere (hopefully in your app controller or somewhere like
that)
and then release it when you're absolutely sure that all your
operations have
run and you don't want to ever add any more.
You /should/, however, autorelease your NSOperation since your queue
will retain it when you add it and release it when it completes.
- (void) stopQueue {
[theQueue cancelAllOperations];
// [theQueue release]; // [ ... autorelease]
[theOp release];
}
You should probably autorelease your Op (unless you want to query it
in the
future after it completes, in which case you should release it when
you're finished
with it). This case will also only release the last operation from
your loop and
all the others will have been leaked.
- (void) startCalculation {
int row;
for (row=1; row < 100; row++) {
// stuff here
[self startQueue]; // start new thread
// [theQueue waitUntilAllOperationsAreFinished];
}
// more stuff
}
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden