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

Boo*_*oon 1 objective-c objective-c-blocks

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

例如,以下代码:

- (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?
}
Run Code Online (Sandbox Code Playgroud)

Cat*_*Man 5

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

  • @Boon,如果块保存对包含它们的对象的引用(给定代码中的`self`)或保持对对象的引用,而对象又引用对该对象的引用(等等),那么就有一个保留周期.如果没有什么打破循环,那么这些对象都不会被解除分配.你是对的**如果**这个对象被解除分配,它将释放它对这些块的引用.但是,清除块引用可能是此对象被释放的先决条件. (2认同)