鉴于您的评论,我可能倾向于追求NSOperationQueue
. 这样你就可以
创建背景NSOperationQueue
;
如果您的下载允许某个合理数量的同时下载,您可以设置maxOperationCount
(或者如果您想要连续下载,请将其设置为 1)。
当您启动后台作业时,您可以创建NSOperation
对象,或者直接NSOperationQueue
通过addOperationWithBlock
. 如果您想享受检查isCancelled
标志的能力,您可能需要执行前者。
每个操作都可以在尝试更新视图控制器之前检查它是否被取消。
当视图控制器被关闭时,它可以执行一个简单cancelAllOperations
的取消所有排队的操作。
这是一个随机的例子:
- (void)viewDidLoad
{
[super viewDidLoad];
self.queue = [[NSOperationQueue alloc] init];
self.queue.maxConcurrentOperationCount = 4;
// let's add 100 operations to our queue
for (NSInteger i = 0; i < 100; i++)
{
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__unsafe_unretained NSBlockOperation *weakOperation = operation; // it seems vaguely disturbing to do this with __unsafe_unretained, but given that the operation queue is taking care of this for us, I believe it's ok
[operation addExecutionBlock:^{
NSLog(@"Beginning operation %d", i);
sleep(10);
if ([weakOperation isCancelled])
NSLog(@"Operation cancelled %d", i);
else
{
// go ahead and update UI if you want
NSLog(@"Finished operation %d", i);
}
}];
[self.queue addOperation:operation];
}
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[self.queue cancelAllOperations];
}