Search code examples
iphonensoperationqueue

While switching view on navigation bar, how to quit NSOperationQueue thread safely without EXC_BAD_ACCESS error


I am using an UITableView to show some string messages, and I use NSOperationQueue to hold an customized NSOperation which fetchs message in background thread. After one message fetched successfully, customized NSOperation will notify the UITableView controller to show it.

If I click back button on the navigation bar to switch from the UITableView to other view after all message loaded, every thing is OK. But, if i click the back button while some message still loading, an EXC_BAD_ACCESS is throw. I have checked that the exception happened while customized NSOperation notify UITableView controller with performSelectorOnMainThread method. Sound like the target UITableView controller is not invalid after view switched, but I think Navigation Controller will hold the view controller instance. May I know how to resolve this issue? Thanks.

Customized operation is initialized in the UITableView controller with following code:

StatusMessageLoadingOperation *operation = [[StatusMessageLoadingOperation alloc] 
                                            initWithData:person
                                            messageArray:cachedStatusMessages
                                            target:self 
                                            action:@selector(didFinishStatusMessages:)];
[operationQueue addOperation:operation];
[operation release];

The customized NSOperation class will update UITableView with following code:

- (void)main{
    for (int i = 0; i < [[person statusMessages] count]; i++) {
        [target performSelectorOnMainThread:action withObject:messageArray waitUntilDone:NO];
    }
}

Solution

  • Have you tried calling [operationQueue cancelAllOperations] in your viewWillDisappear method?