NSInvocationOperation : 'cancel' doesn't work

Discussion in 'iPhone/iPad Programming' started by namanhams, Jul 28, 2010.

  1. macrumors regular

    Joined:
    Jun 3, 2009
    #1
    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 :

    Code:
    [operation cancel];
    doesn't seem work although it's called.

    Any idea ?
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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. macrumors regular

    Joined:
    Sep 11, 2008
    #3
    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. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    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. macrumors regular

    Joined:
    Sep 11, 2008
    #5
    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