0

I want to execute a function before an NSOperation is cancelled. In main function, I add below code to achieve this goal:

if (self.isCancelled) {
    [self doSomething];
    return;
}

But if I cancel an operation before its start method is called, where should I call doSomething?

For queued operations, it simply marks the operation as ready to execute and lets the queue call its start method, which subsequently exits and results in the clearing of the operation from the queue.

According to above Apple's document, I know that I can call doSomething in start function, so am I right?

- (void)start {
    if (self.isCancelled) {
        [self doSomething];
    }
    [super start];
}
Yuwen Yan
  • 4,777
  • 10
  • 33
  • 63

1 Answers1

1

I would set the code you want to run in the completionblock.

Chris
  • 2,727
  • 2
  • 27
  • 28
  • But I don't want to call this function if the operation isn't cancelled – Yuwen Yan Jul 14 '15 at 08:14
  • Thanks Chris, I'm not familiar with NSOperation, since I can't use self. isCancelled in completionblock, so how to check it in completionblock? – Yuwen Yan Jul 15 '15 at 03:48
  • You need to use a weak self. http://stackoverflow.com/questions/9223049/referencing-an-nsoperation-object-in-its-own-completion-block-with-arc – Chris Jul 15 '15 at 07:43