声明变量不能被块捕获

Declare that a variable must not be captured by a Block

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

我想要这样的东西:

[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 需要 Core Data 锁定,我只是将一个锁变成了两个。

你可以只使用作用域块(不是闭包类型的块,只是 C compound-statement 类型的块)来确保 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;