声明块不能捕获变量

时间:2018-03-20 20:32:17

标签: objective-c objective-c-blocks

有没有办法阻止变量被捕获到块中?

我想要这样的东西:

[context performBlockAndWait:^{
    CoreDataObject *coreDataObject = [self getObject];
    NSString *name = coreDataObject.name;
    [self doThingWithCompletion:^{
        // I never want to use coreDataObject here, but I might want to use name.
    }];
}];

是的,这不会捕获coreDataObject。但是,如果我不小心在块中使用它,它会。有没有办法声明永远不应该捕获coreDataObject

到目前为止,我提出的最好的是:

__block NSString *name;
[context performBlockAndWait:^{
    CoreDataObject *coreDataObject = [self getObject];
    name = coreDataObject.name;
}];
[self doThingWithCompletion:^{
    // coreDataObject is no longer in scope here
}];

但是,如果doThingWithCompletion需要核心数据锁定,我只需将一个锁定为两个。

1 个答案:

答案 0 :(得分:3)

您可以使用范围块(不是块的闭包类型,只是C复合语句类型的块)来确保不能使用coreDataObject

[context performBlockAndWait:^{
    NSString *name;

    {
        CoreDataObject *coreDataObject = [self getObject];
        name = coreDataObject.name;
    }

    [self doThingWithCompletion:^{
        // I never want to use coreDataObject here, but I might want to use name.
    }];
}];

在这种简单的情况下,你也可以完全消除coreDataObject变量:

    NSString *name = [self getObject].name;