NSOperationQueue未被取消

时间:2017-03-29 17:08:01

标签: ios objective-c nsoperationqueue nsthread

我正在使用PageViewController我可能有多个图片作为内容。我从服务中获得如下图像。但是,当用户在网络操作仍在进行时单击以关闭视图控制器时,应用程序崩溃。

queue = [[NSOperationQueue alloc] init];
operation = [NSBlockOperation blockOperationWithBlock:^{
            [self addAllImages];
                dispatch_sync(dispatch_get_main_queue(), ^(void) {
                     [self pageViewcontrollerSetup];
            });
        }];
     [queue addOperation:operation];
}

- (void) addAllImages
{
    self.pageImages =[[NSMutableArray alloc] initWithCapacity:self.pageControl.numberOfPages];

    for(id key in [[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"]) {
        NSString *productURL = [NSString stringWithFormat:@"%@%@", PRODUCT_URL, [[[[pElements objectAtIndex:self.selectedIndexPath.row]objectForKey:@"pdetail"] objectForKey:@"images"] objectForKey:key]];
        NSData* productData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productURL]];

        if ([UIImage imageWithData:productData]) {
                [self.pageImages addObject:[UIImage imageWithData:productData]];
        }
    }
}

- (void)closeBtnClicked {

    [queue cancelAllOperations];
}

注意:我正在使用GCD(Grand Central Dispatch)进行多线程处理,但我知道您无法取消它,因此我转向NSOperationQueue

1 个答案:

答案 0 :(得分:0)

取消操作不会神奇地停止代码死机。操作中最多您的代码,定期检查操作是否已被取消,如果是,则退出。