块内的块和变量捕获

时间:2015-03-15 20:46:54

标签: objective-c objective-c-blocks

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

@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?
            }];
        }
    }       
}

2 个答案:

答案 0 :(得分:2)

由于两个块都没有被自己保留,因此没有保留周期。每个块都由它所处的方法保留,当方法完成时,它们释放它们的块。

答案 1 :(得分:1)

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