块中的块和变量捕获

blocks within blocks and variable capture

当我有一个方法从回调中执行工作并且该方法本身引用 class 的属性时,这是否被认为是捕获块的方式的泄漏?

@interface ClassA
- (void)performClassAWorkItem1:(void (^)(NSArray *list, NSError *err)block;
- (void)performClassAWorkItem2:(void (^)(NSString *string, NSError *err)block;
@end

@interface ClassB
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) ClassA *classA;
@end

@implementation ClassB

- (void)manipulateFirstThing {
    __weak typeof(self) weakSelf = self;
    [self.classA performClassAWorkItem1:^(NSArray *list, NSError *err) {
        [weakSelf manipulateSecondThing:list];
    }];
}

- (void)manipulateSecondThing:(NSArray *)list {
    for (NSString *str in list) {
        // Is this causing the name property to get captured, causing a leak?
        if ([str isEqual:self.name]) {  
            NSLog(@"Ok this worked!")
            // Is accessing self.classA like this ok?
            [self.classA performClassAWorkItem2:^(NSString *string, NSError *error) {
            // If I access self.name here, is this also a leak?
            }];
        }
    }       
}

不,这不会导致 self.name 被泄露。当您发送 manipulateSecontThing: 选择器时,对 weakSelf 的强引用作为第一个隐式参数传递(选择器 _cmd 是第二个)。

因为两个块都不是自己保留的,所以没有保留周期。每个块都由它所在的方法保留,当方法完成时,它们会释放它们的块。