清理^块

时间:2012-04-29 19:16:55

标签: ios ios5 objective-c-blocks grand-central-dispatch

以下方法来自书籍 Professional iOS增强现实书(Apress)的github存储库。

基于整个UIViewController的示例中没有任何代码可以处理清理。这里调用的CoreImage面部检测程序可能需要几秒钟才能完成。

如果用户导致更改导致此viewController消失,会发生什么?我理解^块是由队列保留的,这是一个向nil发送消息的情况(当面部检测例程返回时)实际上是一个好处吗?

- (IBAction)detectFacialFeatures:(id)sender {

    self.detectingView.hidden = NO;
    self.scrollView.scrollEnabled = NO;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        CIImage *image = [[CIImage alloc] initWithImage:[FACE_IMAGES objectAtIndex:self.currentIndex]];

        NSString *accuracy = self.useHighAccuracy ? CIDetectorAccuracyHigh : CIDetectorAccuracyLow;
        NSDictionary *options = [NSDictionary dictionaryWithObject:accuracy forKey:CIDetectorAccuracy];
        CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:options];

        NSArray *features = [detector featuresInImage:image];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self drawImageAnnotatedWithFeatures:features];
        });    
    });
}

1 个答案:

答案 0 :(得分:2)

dispatch_async()复制块,因为它会使其超出声明范围。块中引用的所有对象在复制时都会保留。因此,假设您引用的viewController为self,它将不是nil。它将在整个生命周期内保留。

相关问题