PDA

View Full Version : NSInvocationOperation : 'cancel' doesn't work




namanhams
Jul 28, 2010, 10:49 PM
I have a NSInvocationOperation which is added to a NSOperationQueue. The operations basically just print number from 1 -> 1000000. What i want to do, is when the user navigate out of the current view controller, then the operation will be canceled.
But this :

[operation cancel];

doesn't seem work although it's called.

Any idea ?



kainjow
Jul 28, 2010, 10:56 PM
Read the docs for -[NSInvocation cancel]. It doesn't actually cancel it, it just sets some flags. In your code you need to check for [self isCancelled] and stop what you're doing (e.g. break out of the loop) if that's true.

idelovski
Jul 30, 2010, 05:32 PM
I have posted a somewhat related question about NSOperation (http://forums.macrumors.com/showthread.php?t=977382) here recently. I was hoping someone would clarify few things to me, but I got no replies.

In the meantime I was reading few documents at Apple and I think I solved at least something, even though I still have millions of questions about NSOperation/NSOperationQueue.

Most of the operations at the end supply result to the main thread, usually with a call to -performSelectorOnMainThread:withObject:waitUntilDone: and I was worried what would happen if the target object disappeared in the meantime.

Well, the object that started the operations can call -cancelAllOperations on the NSOperationQueue. For example, view controller that is about to be popped off the navigation stack can call -cancelAllOperations before it disappears and operations should check if they were canceled before calling -performSelectorOnMainThread:withObject:waitUntilDone.

PhoneyDeveloper
Jul 30, 2010, 09:47 PM
Millions of questions huh? We could be here all night.

Anyway, the operation should send its performSelectorOnMainThread:withObject:waitUntilDone to itself and then message the delegate on the main thread if it hasn't been cancelled.

idelovski
Jul 31, 2010, 05:49 AM
Millions of questions huh? We could be here all night.

If I only knew... I went to bed just an hour before you answered and it was 4am local time.

Anyway, the operation should send its performSelectorOnMainThread:withObject:waitUntilDone to itself and then message the delegate on the main thread if it hasn't been cancelled.

Oh, this is beautiful. I don't think I would have come to this on my own. So simple, yet solves half a million of my questions. This way I can even pass autoreleased objects to the delegate.

Thank you, thank you, thank you!