Objective-C中的__block关键字到底是什么意思?我知道它允许你在块内修改变量,但我想知道…
它到底告诉编译器什么? 它还有别的功能吗? 如果这就是它所做的一切,那么为什么首先需要它呢? 文档里有吗?(我找不到)。
Objective-C中的__block关键字到底是什么意思?我知道它允许你在块内修改变量,但我想知道…
它到底告诉编译器什么? 它还有别的功能吗? 如果这就是它所做的一切,那么为什么首先需要它呢? 文档里有吗?(我找不到)。
当前回答
这意味着它作为前缀的变量可以在块中使用。
其他回答
__block是一种存储类型,用于使作用域变量可变,更坦率地说,如果你声明一个变量与此说明符,它的引用将被传递给块而不是只读副本,详情请参阅iOS中的块编程
@bbum在一篇博客文章中深入介绍了块,并涉及到__block存储类型。
__block是一种独特的存储类型 就像static、auto和volatile一样,__block也是一种存储类型。它 告诉编译器要管理变量的存储 不同的… 然而,对于__block变量,块不保留。根据需要,您可以保留或释放它。 ...
至于用例,你会发现__block有时被用来避免保留周期,因为它不保留参数。一个常见的例子是使用self。
//Now using myself inside a block will not
//retain the value therefore breaking a
//possible retain cycle.
__block id myself = self;
希望这对你有所帮助
让我们假设我们有这样一个代码:
{
int stackVariable = 1;
blockName = ^()
{
stackVariable++;
}
}
它会给出一个类似“变量不可赋值”的错误,因为块内的堆栈变量默认是不可变的。
在它的声明之前添加__block(存储修饰符),使它在块内部是可变的,即__block int stackVariable=1;
这意味着它作为前缀的变量可以在块中使用。
当你不使用__block时,块会复制变量(按值调用),所以即使你在其他地方修改了变量,块也看不到变化。
__block使块保持对变量的引用(引用调用)。
NSString* str = @"hello";
void (^theBlock)() = ^void() {
NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints @"hello"
在这两种情况下,你需要__block:
If you want to modify the variable inside the block and expect it to be visible outside: __block NSString* str = @"hello"; void (^theBlock)() = ^void() { str = @"how are you"; }; theBlock(); NSLog(@"%@", str); //prints "how are you" If you want to modify the variable after you have declared the block and you expect the block to see the change: __block NSString* str = @"hello"; void (^theBlock)() = ^void() { NSLog(@"%@", str); }; str = @"how are you"; theBlock(); //prints "how are you"