Is there an Objective-C property attribute that mimics the functionality of the __block keyword?
我想创建一个允许块更新其内容的属性。对于一个典型变量(即不是自动合成的变量等),我将在声明前面加上
有没有办法使一个属性能够被一个块更新?
编辑:有些答案说只是为了使用属性设置器方法。我实际上想做的是将对象添加到可变数组中,所以我不想每次都使用
既不是属性局部变量,也不需要在只想向可变数组中添加内容时更改变量。变量不变,它是变量后面的对象状态。
这不是正确的思考方式。要修改具有属性的对象。所以捕获块中的对象,并调用其访问器(
编辑:从各种编辑中,你可能会混淆Objc对象是如何工作的,以及C++是如何工作的。Objc只使用指向对象的指针,很少复制它们,缺少EDOCX1×1对象的概念(有不可变的对象,但这只是因为它们没有变异体;你不能EDCOX1,1)一个像C++一样可变的对象。
1 | __block id foo; |
这意味着可以更改
当您想修改一个块中的变量时,可以使用_uuu块;在这种情况下,您想做的不是修改变量(它仍然指向同一个
没有必要在
Within the block object’s body of code, variables may be treated in
five different ways.You can reference three standard types of variable, just as you would
from a function:Global variables, including static locals Global functions (which aren’t technically variables) Local variables and parameters from an enclosing scope Blocks also support two other types of variable:
At function level are __block variables. These are mutable within the
block (and the enclosing scope) and are preserved if any referencing
block is copied to the heap.const imports.The following rules apply to variables used within a block:
Global variables are accessible, including static variables that
exist within the enclosing lexical scope.Parameters passed to the block are accessible (just like parameters to a function). Stack (non-static) variables local to the enclosing lexical scope are
captured asconst variables.
Their values are taken at the point of
the block expression within the program. In nested blocks, the value
is captured from the nearest enclosing scope.Variables local to the enclosing lexical scope declared with the
__block storage modifier are provided by reference and so are mutable.
Any changes are reflected in the enclosing lexical scope,
including any other blocks defined within the same enclosing lexical
scope.Local variables declared within the lexical scope of the block,
which behave exactly like local variables in a function.
Each
invocation of the block provides a new copy of that variable. These
variables can in turn be used as const or by-reference variables in
blocks enclosed within the block.