关于ios:是否存在一个模仿__block关键字功能的Objective-C属性?

Is there an Objective-C property attribute that mimics the functionality of the __block keyword?

我想创建一个允许块更新其内容的属性。对于一个典型变量(即不是自动合成的变量等),我将在声明前面加上__block

有没有办法使一个属性能够被一个块更新?

编辑:有些答案说只是为了使用属性设置器方法。我实际上想做的是将对象添加到可变数组中,所以我不想每次都使用setProperty:.property =创建一个新的可变数组并将其设置回属性。是否可以在不分配所有内存的情况下修改属性?


__block用于声明块可能要更改的局部变量。

既不是属性局部变量,也不需要在只想向可变数组中添加内容时更改变量。变量不变,它是变量后面的对象状态。


这不是正确的思考方式。要修改具有属性的对象。所以捕获块中的对象,并调用其访问器(setFoo:来修改属性。

编辑:从各种编辑中,你可能会混淆Objc对象是如何工作的,以及C++是如何工作的。Objc只使用指向对象的指针,很少复制它们,缺少EDOCX1×1对象的概念(有不可变的对象,但这只是因为它们没有变异体;你不能EDCOX1,1)一个像C++一样可变的对象。

__block的意思是"这个变量(不是它指向的对象;这个实际变量)应该通过引用传递到块中,而不是通过值传递。"所以当我说:

1
__block id foo;

这意味着可以更改foo指针本身。它与foo所指的对象是否可以变异完全无关。这对于一个全球或一个IVAR来说毫无意义。ivar是隐式结构字段。当您在一个块中说_ivar时,编译器将它隐式转换为self->_ivar,然后捕获self。它不捕获_ivar(因为这只是self结构中的一个偏移)。使用访问器做同样的事情更好,因为它更明确地说明了您在做什么,并且您可以这样使用__weak


当您想修改一个块中的变量时,可以使用_uuu块;在这种情况下,您想做的不是修改变量(它仍然指向同一个NSMutableArray),而是向它发送一条消息(addObject:)。你不需要挡块。


没有必要在@property声明中加入任何内容。因为它们可以被块访问和修改而不需要任何麻烦。根据文件:

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 as const 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.