1

Current status

I have created a custom NSOperation object and I want to update some data when it is cancelled.

I've followed what said in this answer and I didn't override the cancel method.

Here is my header:

// MyOperation.h
@interface MyOperation : NSOperation {
}
@property (nonatomic, retain) OtherDataClass *dataClass;
@end

And the implementation

// MyOperation.m
@implementation MyOperation

@synthesize dataClass;

- (void)main {
    if ([self isCancelled]) {

        [self.dataClass setStatusCanceled];

        NSLog(@"Operation cancelled");
    }

    // Do some work here
    NSLog(@"Working... working....")

    [self.dataClass setStatusFinished];

    NSLog(@"Operation finished");
}

@end

The question

I have several operations in a queue. I was expecting that, when I call cancelAllOperations in the queue, I'll get the "Operation cancelled" text in the log and the status updated in my other class but it is not working. The main method is not being called for the operations in the queue.

Why is this happening and how can I solve it?

Notes

I've tried to overwrite the cancel method with this:

- (void)cancel {
    [super cancel];
    [self.dataClass setStatusCanceled];
    NSLog(@"Operation cancelled");
}

It is working but I've read that this method should not be overridden.

Community
  • 1
  • 1
Octan
  • 348
  • 4
  • 19
  • I don't see why `main` would be called again? i.e you start your NSOperation `main` is called and does its thing. Calling `cancelAllOperations` would not call `main` again as this would just start "the work" again? I don't see anything in the docs stating you should not override `cancel`. Can you give a reference. – sbarow Oct 29 '14 at 10:07
  • I don't want to call `main` more than once. I have, for example, 5 operations in a queue. If I call `cancelAllOperations` when computing the third, I expect obtaining the _"Operation finished"_ for the first two and the current one (when finished) and then the _"Operation cancelled"_ text for the last two ones. But I'm not getting the last two log lines, because `main` doesn't seem to be called for the last two ones, once the queue has been canceled. Regarding overriding `cancel` method, I saw it in several StackOverflow answers. – Octan Oct 29 '14 at 10:13

1 Answers1

2

When you call cancelAllOperations, the operations which are already started will have isCancelled set to YES. operations which aren't already started won't start.

Michał Banasiak
  • 950
  • 6
  • 13