2017-03-29 62 views
0

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

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(大中央调度)多线程,但我才知道,你无法取消,所以我swicthed到NSOperationQueue

回答

0

取消操作不魔法般地停止了你的代码。这是高达您的代码在操作中定期检查,以查看操作是否已被取消,如果是,则退出。

+0

请问你能给我一个小例子吗?我以为'cancelAllOperations'会立即取消相应的线程。如果不是,那么使用'[queue cancelAllOperations]'的目的是什么?''? – hotspring

+0

你看过我发布的链接吗?它向您展示了如何检查您的操作块内的取消操作。 – matt