应用程序在dealloc崩溃 [英] app crash in the dealloc

查看:379
本文介绍了应用程序在dealloc崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序在 dealloc 中崩溃,但有时只会崩溃。

My app crashes in dealloc, but only sometimes.

我创建了一个用于缓存5个对象的数组。当用户点击左右对象时,会添加一个新对象,并删除最后一个对象。当我测试应用程序时,在点击向右或向左按钮100-500次后,应用程序崩溃。

I create one array for caching 5 objects. When the user taps right or left one, a new object is added and the last is removed. When I tested the app, after tapping the right or left button 100-500 times, the app crashes.

应用程序在 dealloc <崩溃/ code>方法但所有对象都已正确分配和释放。

The app crashes in the dealloc method but all objects are allocated and released correctly.

我的 dealloc 方法:

 - (void)dealloc
{
    [super dealloc];
    [_sImageLane release];
    [_sTipoLane release];
    [_maRecomended release];
    [_maProdcucts release]; // here crash in this line EXC_BAD_ACCESSE
}

出了什么问题?

推荐答案

[super dealloc] 放在最后而不是第一位。

Put [super dealloc] last instead of first.

编辑:发生这种情况的原因是由于objc对象的生命周期。当它死亡时,对象将被发送 dealloc 消息。在该方法中,对象必须自我清理,并将消息传递到继承链(因为超类也需要自我清理)。好吧,如果你正确地使用 [super dealloc] 成为最后一个会怎么样?

EDIT : The reason why this happens is due to the lifecycle of an objc object. When it is time for it to die, the object is sent the dealloc message. Inside that method, the object must clean itself up, and pass the message up the inheritance chain (because the super class needs to clean itself up as well). Well, what happens if you do that correctly with [super dealloc] being last?


清理自己的资源 - >清理super上的资源 - >清理super的超级资源 - >等 - >运行时回收的内存。

Clean up resources on self -> clean up resources on super -> clean up resources on super's super -> etc -> memory reclaimed by runtime.

很好,如果你这样做会发生什么?

Nice, well what happens if you do it your way?


清理超级资源 - >清理资源超级 - >等 - >运行时回收的内存 - >清理自己的资源

Clean up resources on super -> clean up resources on super's super -> etc. -> memory reclaimed by runtime -> clean up resources on self

哎呀,现在你正在访问回收的内存并试图与它进行交互(即EXC_BAD_ACCESS或者更糟糕的是,在其他对象的其他地方弄乱内存并且没有意识到它)。

Oops, now you are accessing reclaimed memory and trying to interact with it (i.e. EXC_BAD_ACCESS or worse, messing with memory somewhere else on another object and not realizing it).

NSObject 的dealloc方法实际上释放了内存(可能通过 free()),所以一旦你调用它,你就处于未定义的危险灰色区域。

NSObject's dealloc method literally frees the memory (probably via free()) so once you've called that you are in undefined dangerous gray areas.

这篇关于应用程序在dealloc崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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