Question

In almost every UIViewController I have a bunch of AFHTTPRequestOperations and I have to properly handle any kind of cancel (pressing cancel button, going back in UINavigationController's stack, etc.). I was wondering if creating one NSOperationQueue per each UIViewController and adding to it all operations called within controller would be a proper way to go? I was aiming for cancelling all operations [[NSOperationQueue mainQueue] cancelAllOperations] but this will kill all operations already started, especially those called from previous UIViewController. Or should I create property for each operation, call it in viewWillDissappear:(BOOL)animated and set if statement for cancel state in success block?

Was it helpful?

Solution

AFHTTPRequestOperationManager instances are cheap to create and each has its own operation queue, so it is easy to cancel all of a given UIViewController's operations:

- (void)dealloc {
    [self.requestOperationManager.operationQueue cancelAllOperations];
}

This will cancel any request created through self.requestOperationManager. You can create the AFHTTPRequestOperationManager in your UIViewController's init method.

I recommend cancelling operations in your view controller's dealloc method, as you know it will no longer be needed.

OTHER TIPS

Tried David Caunt answer, but didn't work for me. dealloc wasn't called when I pushed back button, so I guess the best way to cancel operations is to call it in viewWillDisappear: (my bad was to use && not || - silly mistake, but easiest things are often hardest to find)

- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated]; 
if (self.isMovingFromParentViewController && self.isBeingDismissed){
    DDLogDebug(@"back or dismissed!"); 
    [self.manager.operationQueue cancelAllOperations]; } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top