[myArray addObject:[[objcBlock复制]自动释放]]在取消分配数组时崩溃 [英] [myArray addObject:[[objcBlock copy] autorelease]] crashes on dealloc'ing the array

查看:75
本文介绍了[myArray addObject:[[objcBlock复制]自动释放]]在取消分配数组时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个类,用于声明性地描述一系列UIView动画.我的方法采用各种动画块,并将它们放入数组中.所以在我的循环中,我想这样做:

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]];

我首先copy该块,以便将其移动到堆,从而允许该数组对它进行retain运算.然后我自动释放它以放弃所有权(因为数组保留了它).

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.)

奇怪的是,有效:

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

更新: …就像这样:

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

为什么?我本来希望所有3个代码段都能正常工作.有什么解释吗?

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

推荐答案

示例1:

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

这是复制一个块,并自动释放该副本.

This is copying a block, and autoreleasing the copy.

示例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.

示例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.

这篇关于[myArray addObject:[[objcBlock复制]自动释放]]在取消分配数组时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆