NSInvocationOperation : 'cancel' doesn't work

Discussion in 'iOS Programming' started by namanhams, Jul 28, 2010.

  1. namanhams macrumors regular

    Jun 3, 2009
    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 ?
  2. kainjow Moderator emeritus


    Jun 15, 2000
    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.
  3. idelovski macrumors regular

    Sep 11, 2008
    I have posted a somewhat related question about NSOperation 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.
  4. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    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.
  5. idelovski macrumors regular

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

    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!

Share This Page