我正在使用 NSOperation
来收集应该下载的数据(需要 2-5 秒),然后我下载它。我在这个 NSOperation 中放置了一个 ASINetworkQueue 以开始下载之前收集的数据。
一切正常,但是当我在我的 ASINetworkQueue
上调用 cancelAllOperations
时,主线程阻塞并且 UI 卡住。为什么会这样?其他一切正常。
这是我的代码:
- (void)main {
//ManagedObjectContext for operations
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = [[NSManagedObjectContext alloc] init];
[self.managedObjectContext setPersistentStoreCoordinator: [appDelegate persistentStoreCoordinator]];
// Register context with the notification center
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:self.managedObjectContext];
[self startDownload];
if (!self.downloadDidFail) {
[self moveFiles];
[self.managedObjectContext save:nil];
}
}
- (void)startDownload {
self.downloadQueue = [ASINetworkQueue queue];
self.downloadQueue.delegate = self;
[self.downloadQueue setRequestDidFailSelector:@selector(dataRequestFailed:)];
[self.downloadQueue setRequestDidFinishSelector:@selector(dataRequestFinished:)];
[self.downloadQueue setQueueDidFinishSelector:@selector(dataQueueFinished:)];
[self.downloadQueue setShouldCancelAllRequestsOnFailure:YES];
[self.downloadQueue setDownloadProgressDelegate:self.progressView];
for (File *dataFile in self.dataFiles) {
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:dataFile.url]];
[request setDownloadDestinationPath:dataFile.path];
[self.downloadQueue addOperation:request];
}
}
[self.downloadQueue go];
[self.downloadQueue waitUntilAllOperationsAreFinished];
}
- (void)dataRequestFinished:(ASIHTTPRequest *)request {
NSLog(@"DL finished");
}
- (void)dataRequestFailed:(ASIHTTPRequest *)request {
DLog(@"Download failed");
self.downloadDidFail = YES;
}
- (void)dataQueueFinished:(ASINetworkQueue *)queue {
DLog(@"Finished Data Queue");
}
- (void)cancelDownload {
self.canceledDownload = YES;
[self.downloadQueue cancelAllOperations];
}
最佳答案
我遇到了同样的问题,通过调用解决了:
[queue setShouldCancelAllRequestsOnFailure:NO]
调用前:
[queue cancelAllOperations].
关于objective-c - NSOperation 中的 ASINetworkQueue 阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8559995/