2013年3月16日星期六

Blocks and Variables

对于 Block 的用法,一定要注意下面的红字。

如果使用的是自定义的 Block,并且这个 Block 在某个对象的生命周期内会一直存在,一定要注意红字,遵循规则。
否则,则很容易出现 retain cycle。
所以,现在官方的 Api 提供的 block 使用,也是类似动画这种 block,它只在某个对象的生命周期内出现瞬间,然后销毁,这样就不会有 retain cycle。


Objective-C Objects

  1. In a manually reference-counted environment, local variables used within the block are retained when the block is copied. Use of instance variables within the block will cause the object itself to be retained. If you wish to override this behavior for a particular object variable, you can mark it with the __block storage type modifier.
  2. If you are using ARC, object variables are retained and released automatically as the block is copied and later released.

Note In a garbage-collected environment, if you apply both __weak and __block modifiers to a variable, then the block will not ensure that it is kept alive.


  1. If you use a block within the implementation of a method, the rules for memory management of object instance variables are more subtle:
  2. If you access an instance variable by reference, self is retained;
  3. If you access an instance variable by value, the variable is retained.

The following examples illustrate the two different situations:

dispatch_async(queue, ^{
      // instanceVariable is used by reference, self is retained
      doSomethingWithObject(instanceVariable);
  });
  id localVariable = instanceVariable;
  dispatch_async(queue, ^{
      // localVariable is used by value, localVariable is retained (not self)
      doSomethingWithObject(localVariable);
  });


C++ Objects
In general you can use C++ objects within a block. Within a member function, references to member variables and functions are via an implicitly imported this pointer and thus appear mutable. There are two considerations that apply if a block is copied: 

没有评论:

发表评论