-1

我有 NSURLSession,它从服务器下载新的用户配置文件,然后为每个配置文件下载照片数组,然后存储在 Core Data 中。每次用户到达此屏幕时,我都会停止下载任务,清除核心数据,然后再次填充。问题是,cancel() 函数是异步的,所以它在我清除核心数据后设法保存一些配置文件。此外,由于数据任务取消,这些配置文件可能没有一些数据。那么,问题来了——如何正确完成下载任务,然后清除核心数据?提前致谢。

4

1 回答 1

2

我会建议使用NSOperation类来满足您的需要。

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/

您应该完成将数据下载到 NSOperation 类的操作,并且在将结果添加到 CoreData 之前,您可以检查 NSOperation 是否在两者之间被取消。

@interface DownloadOperation: NSOperation
@end

@implementation DownloadOperation
- (void)main {
    @autoreleasepool {
        [Server downloadDataFromServer:^(id results) {
             if (self.isCancelled == NO)
             {
                [CoreData saveResults:results];
             }
        }];
    }
}
@end

您将操作添加到 NSOperationQueue:

NSOperationQueue *queue= [[NSOperationQueue alloc] init];
[queue addOperation:[[DownloadOperation alloc] init]];

您可以通过调用取消它:

[operation cancel];

或取消所有操作:

[queue cancelAllOperations];
于 2015-09-01T20:16:42.597 回答