When storing blocks in properties, arrays or other data structures, there’s an important difference between using
retain. And in short, you should always use
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.
retain a 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 you
copy a 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 you
copy a heap allocated block, it doesn’t copy it again, it just
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, always
An excellent guide on the subject by Joachim Bengtsson can be found here.