[myArray addObject:[[objcBlock copy] autorelease]] crashes on dealloc'ing the array

ぃ、小莉子 提交于 2020-01-01 11:58:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!