-
Copy vs retain for Objective-C blocks
When storing blocks in properties, arrays or other data structures, there’s an important difference between using
copyorretain. And in short, you should always usecopy.When blocks are first created, they are allocated on the stack. If the block is called when that stack frame has disappeared, it can have disastrous consequences, usually a EXC_BAD_ACCESS or something plain weird.
If you
retaina stack allocated block (as they all start out being), nothing happens. It continues to be stack allocated and will crash your app when called. However, if youcopya stack allocated block, it will copy it to the heap, retaining references to local and instance variables used in the block, and calling it will behave as expected. However, if youcopya heap allocated block, it doesn’t copy it again, it justretainsit.So you should always declare your blocks as properties like this:
@property (copy, ...) (int)(^aBlock)();And never like this:
@property (retain, ...) (int)(^aBlock)();And when providing blocks to
NSMutableArrays and the like, alwayscopy, neverretain.An excellent guide on the subject by Joachim Bengtsson can be found here.
Posted on September 21, 2011 with 20 notes ()
-
refractalize posted this
-