views:

430

answers:

2

Hi!

I'm calling a NSOperation from a Subview of a NavigationController.

MyOperation *op = [[MyOperation alloc] target:self action:@selector(didFinishOperation)];

The Operation loads some data from a server, parses it and then sends a

[target performSelectorOnMainThread:action withObject:nil waitUntilDone:YES];

when the job is done. This is generally working...

The problem is when I push the back button from the navigation controller while the NSOperation is doing its job, the app crashes because the action references a deallocated instance.

I've tried retaining the operation - but it still crashes...

Thanks in advance

A: 

In your UIView dealloc method, you could cancel the operation and remove it from its NSOperationQueue.

Chris Gummer
+2  A: 

Chris is on the right track, but it doesn't cover the case where the operation completes as you try to cancel it, and it will still crash. If the operation is executing in main, the cancel won't take effect.

Still, try and cancel it before your target is destroyed, but test that the target still exists before attempting to send it a message. Also, check if you're cancelled before trying to send the message:

if ( self.isCancelled ) return;
ohhorob
I've already cancel the operations in viewWillDisappear:[operationQueue cancelAllOperations];I run more than 1 operation when loading the view.As you mentioned above - this will cancel the operations but not if its executing in main.I've tried:if (target)[target performSelectorOnMainThread:action withObject:nil waitUntilDone:YES];but the error still occurs...
abs
I just reviewed my code, and my operations check if they're cancelled before attempting to notify their target.
ohhorob
Thanks ohhorob,that did the job :)
abs