简体   繁体   中英

cleaning up ^blocks

The method below is from a github repository for the book Professional iOS Augmented Reality book (Apress).

There isn't any code in the overall UIViewController -based example which deals with clean up. The CoreImage face detection routine called here could take a few seconds to complete.

What happens if the user causes a change resulting in this viewController disappearing? I understand the ^block is retained by the queue, Is this a case where sending a message to nil (when the face detection routine returns) is actually a benefit?

- (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];
        });    
    });
}

dispatch_async() copies the block, because it will keep it beyond its declaration scope. All objects referenced in block are retained when it is copied. So, assuming that the viewController to which you're referring is self , it won't be nil . It will have been retained for the life of the block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM