iOS 4 blocks and retain counts

喜你入骨 提交于 2019-12-02 13:59:49

No. The problem occurs when your block retains an object which retains it. Your block will retain any object that it references, except for those annotated with __block. Hence:

// The following creates a retain cycle which will leak `self`:
self.block = ^{
  [self something];
};

self retains block, and block implicitly retains self. This will also happen if you reference instance variables of self.

// The following avoids this retain cycle:
__block typeof(self) bself = self;
self.block = ^{
  [bself something];
};

Variables annotated with __block are mutable (for pointers, that is, the address they point to can be changed); as a result, it makes no sense to retain that object, since you need to treat that object as a local variable (as in, it can be reassigned, affecting an object outside the scope of the block). Thus, __block don't get retained by blocks.

But, now you can run into unforeseen problems if you try to use this block in certain ways. For instance, if you decide to delay the invocation of this block somehow, and self has been deallocated by the time you execute that block, your program will crash, since you're sending a message to a deallocated object. What you need then is a weak reference, which is not provided out-of-the-box in the non-garbage-collected environment!

One solution is to use MAZeroingWeakRef to wrap your block; this will zero out the pointer so that you'll just end up sending messages to nil should you attempt to message self after self has been deallocated:

MAZeroingWeakRef *ref = [MAZeroingWeakRef refWithTarget:self];
self.block = ^{
  [ref.target something];
};

I've also implemented a weak reference wrapper in Objective-C++, which provides the benefit of a more lightweight syntax:

js::weak_ref<SomeClass> ref = self;
self.block = ^{
  [ref something];
};

Because js::weak_ref is a class template, you'll get handy strong-typing (that is, you'll get warnings at compile-time if you try to send the reference a message which it doesn't appear to respond to). But Mike's MAZeroingWeakReference is a lot more mature than mine, so I'd suggest using his unless you want to get your hands dirty.

To read more about issues with __block and the use-case for weak references, read Avoiding retain cycles with blocks, a right way and Jonathan Rentzsch's response.

I'd say it depends what you're doing with your block. If you're not storing it anywhere and use it in the definition place (like sorting an array using a block), then it gets released along with variables referenced inside it (since it's created in stack and is marked for autorelease). If you're storing it somewhere (an array, dictionary or probably pass the block to some other function) copy the block and balance it out with autorelease before passing it along.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!