On Oct 6, 2010, at 1:53 PM, eveningnick eveningnick wrote:
> Hello
> I have an application that transforms a very big file, and during that
> operation i want to give a chance to user to press Esc and cancel this
> transformation. Therefore i need to make mainRunLoop run inbetween
> some "phases" of the file transformation.
It will be much easier to use a custom subclass of NSOperation for this kind of
problem.
The operation's -main method should perform the transformation in a peace-wise
manner and thereby repeatedly checking its cancelation state (-isCancelled
method), like:
- (void) main {
// runs on a secondary thread
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
...
while (![self isCancelled] && !done) {
// transform a peace of data
...
}
[delegate fileTransformOperationDidFinish:self];
[pool release];
}
You add the operation to a NSOperationQueue instance which schedules its
operations onto a secondary thread. From your main thread you may then cancel
the operation by sending it the -cancel message.
There are several ways to notify the application (or some object) when the task
is finished. Using a delegate is safe and easy. You may consider to define a
protocol for the delegate. The delegate method may also schedule its actual
work to the main thread (via
-performSelectorOnMainThread:withObject:waitUntilDone:) if this is necessary.
Just be careful when your task requires itself a runloop (e.g. using
asynchronous NSURLConnection) - since there exists no (implicit) one when
invoking an NSOperation's -main method on a secondary thread. Properly
implementing this will require more elaborated code, though.
Andreas
_______________________________________________
Cocoa-dev mailing list ([email protected])
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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]