如何解决iOS内存错误

由于iOS5.0之前没有自动应用计数机制,也没有Java那样的垃圾回收功能。我们都需要自己管理和控制对象的回收,这是一件很麻烦的事情,也是做iOS项目中最容易出现的问题。如果不掌握这些方法,调试这些问题几乎没有头绪。

1、EXC_BAD_ACCESS内存错误与NSZombieEnabled

EXC_BAD_ACCESS是最常见的错误了,这个一般是访问了释放了的内存地址空间造成的。比如一个对象已经dealloc了,如果你仍向这个对象发送消息,就会出现这个错误。由于出现这个错误时,几乎不显示什么有用的信息,我们根本无法确定程序错在何处。使用NSZombieEnabled环境变量可以很好的解决这个问题。
打开你的工程,选择菜单“Product->Edit Scheme”或快捷键“Commend+<”

NSZombieEnabled环境变量使释放的内存继续保持对象的信息,如果我们向一个已经释放的对象发送一个消息,我们会得到一个错误消息,而且程序自动断点到出错的位置。如我们向一个已经释放了的UIButton对象发送description消息,就会在调试终端上得到以下消息:

*** -[UIButton description]: message sent to deallocated instance 0x1580f360

此时,程序将自动断点到”[UIButton description];”这行代码上。

 

2、Framework内部对象出现Overrelease与MallocStackLoggingNoCompact

通过NSZombieEnabled环境变量,我们可以很多Bug了。但有时错误发生在framework内部,这时断点的当前栈并不在我们的代码当中。比如:

xxx: *** -[CALayer release]: message sent to deallocated instance 0xe250df0

这个CALayer并不是我们直接创建,而且release消息也不发生在我们的代码中。我们完全不知道这个CALayer是那个View的。所以就没法明确那个类出现问题。如果知道这个CALayer在什么地方alloc的就好了,这时我们就需要MallocStackLoggingNoCompact环境变量了。这个环境变量开启的alloc日志,它会记录每个对象alloc时的栈的情况。根据栈的情况我们就可以弄清楚那个类初始化了这个Layer,从而检查代码解决问题。设置方法和NSZombieEnabled类似:

当message sent to deallocated instance消息产生时,在调试终端输入:

info malloc-history 0xe250df0

就会打印layer alloc时栈的情况,可以看到代码调用情况,找到我们自己的代码,检查代码并修改吧。


Profile your application in the simulator with 'Zombies' Instrument.

Run your app for a while and do whatever you have to do to make your app crash. When it does, you will get a pop up like the image below and it will halt the profiling of the app:

Zombie accessed

Then if you click on the little arrow next to the address (0x158b3c00) .. it will take you to the object retain/release history for the object that was over released (the zombie).

If you highlight the line above where the retain count went to -1, and open View -> Extended detail, it should point you to the stack trace and line in your code where the object was overreleased:

Stack trace

If you double click the class where it is occuring, it will open up your source and show you the bad line of code:

over released code


原文地址:https://www.cnblogs.com/zsw-1993/p/4879903.html