Search code examples
objective-cmultithreadingperformselector

Cancel background request for view when disappear


I have some view that is loading images in the background with

[self performSelectorInBackground:@selector(loadImages:) withObject:nil];

Problem is that if I cancel this view while the method is processing, when it is done, it is trying to reload a UITableView that doesn't exist.

Should I cancel the background request when I cancel the view? how can I do that?

If I check for nil on the table, it's still show a pointer to the table even that i am in another page.


Solution

  • You shouldn't use performSelectorInBackground:withObject:, because it would be better to use NSOperationQueue and the support that it (and NSOperation) offer for cancelling activity. Then, when the view is hidden just call [operationQueue cancelAllOperations].

    (you obviously need to write the operation to consider if it has been cancelled...)

    That said, whatever loadImages: does in the background can still be cancelled by checking the status of the controller before it tries to use the result. You haven't shown the method contents, but that could be checking that a BOOL on the controller (say isCancelled) is NO, or that the controllers view has a superview.