阻止处理程序完成后是否应该为零?

时间:2014-05-31 03:45:46

标签: objective-c objective-c-blocks

当类完成运行时,是否所有传递的块处理程序都是nil out?如果没有一个块完全没有,会发生什么?

例如,以下代码:

- (void)runWithCompletionHandler:(void (^)(id results))completion
                  failureHandler:(void (^)(NSError *))failure {

    self.completionHandler = completion;
    self.failureHandler = failure;

    [self run];
}

// Run will be overridden by subclass and 
// finishWithResults will be called when subclass is done
- (void)run {
    [self finishWithResults:nil];
}

- (void)finishWithResults:(id)results {
    if (self.completionHandler) {
        self.completionHandler(results);
        // Question: Is it necessary to nil out the completion handler?
        self.completionHandler = nil;
    }

    // Question: Should failure handler be nil out here as well?
}

- (void)finishWithErrors:(IHRCarPlayContent *)errors {
    if (self.failureHandler) {
        self.failureHandler(errors);
        self.failureHandler = nil;
    }

    // Question: Should completion handler be nil out here as well?
}

1 个答案:

答案 0 :(得分:5)

这通常是一个好主意,因为这意味着将释放由完成处理程序捕获的任何对象。这有助于减少内存使用量,特别是有助于打破保留周期。