如何停止Dispatch Queue

时间:2012-11-23 06:36:42

标签: iphone multithreading ios5 grand-central-dispatch dispatch

我正在使用Dispatch Queue加载图像,但如果我不希望它在某个时刻加载所有图像,我不知道如何停止队列。

- (void) loadImageInBackgroundArr1:(NSMutableArray *)urlAndTagReference {
    myQueue1 = dispatch_queue_create("com.razeware.imagegrabber.bgqueue", NULL);        
    for (int seriesCount = 0; seriesCount <[seriesIDArr count]; seriesCount++) {
        for (int i = 0; i < [urlAndTagReference count]; i++) {
            dispatch_async(myQueue1, ^(void) {
                NSData *data0 = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[urlAndTagReference objectAtIndex:i]]];
                UIImage *image = [[UIImage alloc]initWithData:data0];
                dispatch_sync(dispatch_get_main_queue(), ^(void) {

                for (UIView * view in [OD_ImagesScrollView subviews]) {

                    if ([view isKindOfClass:[UIView class]]) {

                        for (id btn in [view subviews]) {
                            if ([btn isKindOfClass:[UIButton class]]) {

                                                   UIButton *imagesBtn = (UIButton *)btn;
                        for (UIActivityIndicatorView *view in [imagesBtn subviews]) {
                            if ([view isKindOfClass:[UIActivityIndicatorView class]]) {
                                if (imagesBtn.tag == seriesCount*100+100+i) {
                                    if (view.tag == seriesCount*100+100+i) {
                                        [imagesBtn setImage:image forState:UIControlStateNormal];
                                        [view stopAnimating];
                                        [view removeFromSuperview];
                                        view = nil;
                                        imagesBtn = nil;
                                    }
                                }
                            }
                        }
                      }
                     }
                   }
                }  

            });

            [image release];
            image = nil;
           [data0 release];
            data0 = nil;
        });

    }
}

}

1 个答案:

答案 0 :(得分:7)

调度队列不支持取消。两个明显的选择:

  1. 将您自己的取消标记保存为实例变量,并在继续其工作之前使块检查该标志。所有块都将运行,但设置取消标志后运行的块将很快返回。

  2. 使用NSOperationQueue代替调度队列。 Operation queues support cancelling。如果在开始运行之前取消操作,则根本不会运行。如果操作已在运行,则不会中断,但您可以检查其isCancelled标志并提前返回。