我正在使用NSOperation收集应下载的数据(需要2到5秒钟),然后再下载。我已在此NSOperation中放入ASINetworkQueue,开始下载以前收集的数据。

一切正常,但是当我在cancelAllOperations上调用ASINetworkQueue时,主线程块和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];
}

最佳答案

为了库设计目的,ASI请求响应和队列响应被故意移到主线程。
您有两种解决方案:
-子类ASIHTTPRequest并覆盖2个方法。 (在代码中寻找类似“主线程的子类”的东西)。
-修改库。 (很简单,但是我个人不喜欢这种解决方案)。

关于objective-c - NSOperation内部的ASINetworkQueue阻塞主线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8559995/

10-10 20:37