Why are __block variables not saved (in a non-ARC environment)?

I read the __ block variables documentation and thought about cases when I use __block. It seems to me that I need this in two cases:

  • To mark a variable as read and write when used in a block
  • To avoid saving loops when accessing yourself inside a block

On the surface, it does not look like these two things are connected. I believe that __block variables are not saved as yet another trick that I need to remember for the specific case of using avoiding save cycles.

I am wondering if there is a more important architectural reason why they cannot be kept? I would have thought that another keyword to indicate this might be clearer so as not to mix the two functions listed above.

update -

I should mention that this is code that does not use ARC. Now I see that __block variables are actually stored in ARC.

+6
source share
1 answer

__block variables are not saved if you use manual reference counting. The reason can be found here: http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html :

A simple workaround is that __block variables __block not persisted. This is because such variables are mutable and automatic memory management of them will require each mutation to generate a memory management code behind the scenes. This was considered as too intrusive and difficult to access, especially since a block can be executed simultaneously from several threads.

and also here: http://lists.apple.com/archives/objc-language/2009/Dec/msg00100.html

It is not possible to correctly and efficiently manage accounts when re-assigning a value within a variable.

(I could not find the "official" link in the Apple documentation.)

As described in the Transition to ARC Release Notes , this behavior has changed with ARC:

In manual reference counting mode __block id x; valid without saving x . In ARC mode __block id x; x is saved by default (just like all other values). To get manual reference counting behavior in ARC, you can use __unsafe_unretained __block id x; . However, since the name __unsafe_unretained implies that an unchecked variable is dangerous (because it can hang out) and is therefore discouraged. The two best options are either to use __weak (if you do not need to support iOS 4 or OS X v10.6), or set __block to nil to interrupt the save cycle.

+12
source

Source: https://habr.com/ru/post/948398/


All Articles