gpt4 book ai didi

objective-c - __block 的替代语法?

转载 作者:太空狗 更新时间:2023-10-30 03:08:49 24 4
gpt4 key购买 nike

我对 __block 变量的语法有疑问。我知道您可以在范围内的变量上使用 __block ,因此它在 block 内不是只读的。然而在apple docs中的一个位置,我看到了一个替代方案:

"Variables in the defining scope are read-only by default when used in a block. If you need to change the value of such a variable, you can use a special syntax:

int count = 0;
float cumulativeValue = 0.0;
UpdateElements( a, N, ^(float element){
|count, cumulativeValue|
float value = factor * element;
++count;
cumulativeValue += value;
return value;
} );

In this example, count and cumulativeValue are modified inside the block, so they are included in comma-separated list of shared variables at the beginning of the block scope.

这种语法看起来更简洁,我假设您可以修改未声明但仍在范围内的变量。但是,我在其他任何地方都没有看到这个,而且 xCode 编译器不喜欢我的基本 block 。这是合法的语法吗?

最佳答案

哇。好久没看到这种语法了。

这是在 block 开发过程中探索的各种句法结构之一。它最终被拒绝了,因为它在声明意图时过于不精确并且由此产生的行为会令人困惑。

考虑一个包含三个 block 的作用域,其中两个 block 通过 |a| 将一个变量声明为读写。无法从作用域顶部的 int a = 5; 声明知道该变量的值在 block 的某些作用域中是可读写的。

此外,这会使编译器实现变得更加困难。 C 中的传统是变量存储类型在声明时是固定的。支持这种语法会打破这种期望。

因此,决定使用类似于 volatilestatic 的存储类型修饰符。 __block 之所以被使用,主要是因为 __ 前缀大大减少了会因添加裸关键字而中断的代码量。

感谢您提出这个问题。已提交错误,最终将修复和/或删除该文档。

关于objective-c - __block 的替代语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16988818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com