NSInvocationOperation from started from a view controller and the view controller is disposed?
Suppose I'm doing some iPhone development and I have a subclass of UIViewController
. And suppose this view controller has a NSOperationQueue
which is created in viewDidLoad
and released in dealloc
.
Now suppose at some point while this view controller is alive, it adds an NSInvocationOperation
to the NSOperationQueue
and the operation queue starts executing it in the background. While it's executing, the view controller is dismissed.
What happens to the running NSInvocationOperation
? Could it continue to run and prevent the view controller from being released?
Example code in the view controller:
NSInvocationOperation *operationDoSomething = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(synchronousDoSomething:) object:nil];
[_operationQueue addOperation:operationDoSomething];
[operationDoSometh开发者_如何转开发ing release];
and then this is another function in my view controller:
- (void)synchronousDoSoemthing
{
[NSThread sleepForTimeInterval:1000.0];
[self finished];
}
So in the above example, by the time [self finished]
is called, the view controller has been popped off of the navigation controller.
Yes this is not good. Since viewcontrollers are things that come and go, you should not let them own resources that spwan threads and certainly not a NSOperationQueue
.
A better approach would be to create some global (singleton) object that owns the queue. Your viewconroller can then register itself as an observer to receive messages about completed tasks. Or simply listen to notifications that this global object sends out.
精彩评论