refractalize!

  1. Search
  2. About
  3. Subscribe
  4. Archive
  5. Random
what I work on
  1. PogoScript
  2. GitHub

refractalize!

eyes melt skin explodes everybody dead

discovering software design, programming language design, interaction design and new media

Newer
Older
  • Copy vs retain for Objective-C blocks

    When storing blocks in properties, arrays or other data structures, there’s an important difference between using copy or retain. And in short, you should always use copy.

    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 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 retains it.

    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 copy, never retain.

    An excellent guide on the subject by Joachim Bengtsson can be found here.

    Tagged: blocks objective-c programming tech

    Posted on September 21, 2011 with 20 notes ()

    1. refractalize posted this

Field Notes Theme. Designed by Manasto Jones. Powered by Tumblr.