autorelease]] crashes on dealloc'ing the array

I wrote a class for declaratively describing a sequence of UIView animations. My method takes a vararg of animation blocks and puts them in an array. So in my loop I want to do this:

[animations addObject:[[block copy] autorelease]];

I first copy the block so that it is moved to the heap, allowing it to be retain‘ed by the array. Then I autorelease it to relinquish ownership (because the array retains it).

  • Scripting Animation blocks iOS
  • Performing block operations on objects in array and completing when all complete
  • Objective-C callback handler
  • does dispatch_async copy internal blocks
  • Return Result of Completion Block
  • Is there an advantage to using blocks over functions in Objective-C?
  • However this crashes when the animations array is dealloc’d. (My understanding is that the referenced blocks have already been dealloc’d.)

    Strange thing is, this works:

    [animations addObject:[block copy]];
    [block release];
    

    UPDATE:
    … as does this:

    [animations addObject:[block copy]];
    [block autorelease];
    

    Why? I would have expected all 3 code snippets to work equally well. Any explanation?

    Solutions Collect From Internet About “autorelease]] crashes on dealloc'ing the array”

    Example 1:

    [animations addObject:[[block copy] autorelease]];
    

    This is copying a block, and autoreleasing the copy.

    Example 2:

    [animations addObject:[block copy]];
    [block release];
    

    This is copying a block, then releasing the original. If you’ve handled memory well, this should result in your original block being overreleased (and crashing), and your copy being leaked.

    Example 3:

    [animations addObject:[block copy]];
    [block autorelease];
    

    This is copying a block, then autoreleasing the original. See note with previous example.

    Your answer, then, is that your code is doing something wrong elsewhere. Fix that, and go back to your first example.