objective-c - NSOperation 中的 ASINetworkQueue 阻塞主线程

标签 objective-c ios asihttprequest nsoperation

我正在使用 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/

相关文章:

ios - 如何执行自定义单元格的方法

objective-c - 为什么不调用dealloc?

ios - 使用静态库符号化应用程序的崩溃日志

iphone - 应用程序在访问 NSDictionary 的值时崩溃但在访问其键时不崩溃?

iphone - ASIHTTPRequest 将数据从 iPhone 发布到 PHP

iphone - 为什么我的 ASIHTTPRequest 文件显示 ARC 错误?

ios - 选择时停止 SWRevealViewController 动画

objective-c - NSURL url 值未分配

objective-c - 如何将单个 UITabelViewCell 的高度设置为常量值?

ios - 如何访问公共(public)方法 objective-c 中的属性