title: iPhone - return from an NSOperation
body: <p>I am using a subclass of NSOperation to do some background processes. I want the operation to be cancelled when the user clicks a button.</p>
  
  <p>Here's what my NSOperation subclass looks like</p>
  
  <pre><code>- (id)init{
      self = [super init];
      if(self){
          //initialization code goes here
          _isFinished = NO;
          _isExecuting = NO;
      }
  
      return self;
  }
  
  - (void)start
  {
      if (![NSThread isMainThread])
      {
          [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
          return;
      }
      [self willChangeValueForKey:@"isExecuting"];
      _isExecuting = YES;
      [self didChangeValueForKey:@"isExecuting"];
  
      //operation goes here
  }
  
  - (void)finish{
      //releasing objects here
  
      [self willChangeValueForKey:@"isExecuting"];
      [self willChangeValueForKey:@"isFinished"];
  
      _isExecuting = NO;
      _isFinished = YES;
  
      [self didChangeValueForKey:@"isExecuting"];
      [self didChangeValueForKey:@"isFinished"];
  }
  
  - (void)cancel{
      [self willChangeValueForKey:@"isCancelled"];
  
      [self didChangeValueForKey:@"isCancelled"];
      [self finish];
  }
  </code></pre>
  
  <p>And this is how I am adding objects of this class to a queue and listening for KVO notifications</p>
  
  <p>operationQueue = [[NSOperationQueue alloc] init];
  [operationQueue setMaxConcurrentOperationCount:5];
  [operationQueue addObserver:self forKeyPath:@"operations" options:0 context:&amp;OperationsChangedContext];</p>
  
  <pre><code>- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  {
      if (context == &amp;OperationsChangedContext) {
          NSLog(@"Queue size: %u", [[operationQueue operations] count]);
      }
      else {
          [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
      }
  }
  </code></pre>
  
  <p>To cancel an operation (on a button click for instance), I tried calling -cancel but it doesn't make a difference. Also tried calling -finish but even that doesn't change anything.</p>
  
  <p>Every time I add an operation to the queue, the queue size only increases. finish is called (checked using NSLog statements) but it doesn't really end the operation. I'm still not very confident I'm doing this right</p>
  
  <p>Can someone please tell me where I am going wrong?</p>
  
  <p>Thanks a lot</p>