Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

You could check to see whether your table view is visible or not on screen before reloading it. You could write a helper method or even better a category on UIView that tells whether the given view is visible or not.

Declare isVisibleOnScreen Method on a category on UIView and implement it like this.

- (Bool)isVisibleOnScreen {

    CGRect viewFrame = self.frame;
    CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
    return CGRectIntersectsRect(viewFrame, appFrame);

}

But a better way to do async work is using Grand Central Dispatch. It gives you more control over async work.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top