问题
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).
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?
回答1:
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.
来源:https://stackoverflow.com/questions/5854965/myarray-addobjectobjcblock-copy-autorelease-crashes-on-deallocing-the-a