Home Database Mysql Tutorial 解决EXC_BAD_ACCESS错误的一种方法--NSZombieEnabled

解决EXC_BAD_ACCESS错误的一种方法--NSZombieEnabled

Jun 07, 2016 pm 03:50 PM
access method solve mistake

我们做iOS 程序开发时经常用遇到 EXC_BAD_ACCESS 错误导致 Crash,出现这种错误时一般 Xcode 不会给我们太多的信息来定位错误来源,只是在应用 Delegate 上留下像 Thread 1: Program received signal:EXC_BAD_ACCESS ,让问题无从找起。 比如你对已释放的对

我们做iOS 程序开发时经常用遇到 EXC_BAD_ACCESS 错误导致 Crash,出现这种错误时一般 Xcode 不会给我们太多的信息来定位错误来源,只是在应用 Delegate 上留下像Thread 1: Program received signal:"EXC_BAD_ACCESS",让问题无从找起。

比如你对已释放的对象发送消息时就会出现,EXC_BAD_ACCESS,再如release 的对象再 release,release 那些autorelease 的对象等也会报这样的错。默认设置下 Xcode 不会给你定位具体是哪一行代码,不该去使用已释放的对象,或者release 用错了。

比如 UIViewController 子类中这样的代码:

[cpp] view plaincopyprint?

  1. static NSMutableArray*array;  
  2.    
  3. -(void)viewDidLoad  
  4. {  
  5.     [superviewDidLoad];  
  6.     array= [[NSMutableArray alloc]initWithCapacity:5];  
  7.     [array release];//释放掉该数组  
  8. }  
  9.    
  10. - (void)viewWillAppear:(BOOL)animated{     
  11.     [array addObject:@"Hello"];//使用释放掉的数组  
  12. }  

上面的代码就会出现EXC_BAD_ACCESS 错误,但我执行时 Xcode 一出错却是定位在我在 AppDelegate 的 application:didFinishLaunchingWithOptions: 方法上的某行了,如果代码量多了,要查找具体问题非常难,但凭经验了。

不过NSZombieEnabled 环境变量可以帮我们的忙,就是当设置NSZombieEnabled环境变量后,一个对象销毁时会被转化为_NSZombie,设置NSZombieEnabled后,当你向一个已经释放的对象发送消息,这个对象就不会向之前那样Crash或者产生一个难以理解的行为,而是放出一个错误消息,然后以一种可预测的可以产生debug断点的方式消失, 因此我们就可以找到具体或者大概是哪个对象被错误的释放了。 

对 Xcode 设置了NSZombieEnabled 之后,Xcode 会明确定位在行[array addObject:@"Hello"],然后控制台下报的错误信息是:

*** -[__NSArray addObject:]:message sent to deallocated instance 0x6557370

如何设置 NSZombieEnabled 呢,在 Xcode3 和 Xcode4 下设置不一样,Xcode4 下设置很简单。
Xcode3 下 NSZombieEnabled 设置方法如下:

1.   在XCode左边那个Groups& Files栏中找到Executables,双击其中的一项,或者右键Get Info;
2.  切换到Arguments 
3.  这里一共有两个框,在下面那个Variables to be set in theenvironment:点+号添加一项,Name里填NSZombieEnabled,Value填Yes,要保证前面的钩是选中的。

Xcode4 下设置 NSZombieEnabled 的方法:

你可以点击 Xcode4 菜单 Product -> Edit Scheme-> Arguments, 然后将点击”加号”, 将 NSZombieEnabled 参数加到Environment Variables 窗口中, 后面的数值写上 ”YES”.

或者在 Xcode4 菜单 Product -> EditScheme -> Diagnostics 设置窗口中直接勾上Enable ZombieObjects 即可,Xcode 可用 cmd+shift+进到这个窗口。

解决EXC_BAD_ACCESS错误的一种方法--NSZombieEnabled

Xcode4 已经考虑到了现在的要求,所以提供了更便捷的设置的方式,你也可以在这个窗口中设置其他一些参数,你肯定能由此获得更多的帮助信息。

另外再说一下,如果没有为 Xcode 设置 NSZombieEnable,像下面的代码或许可以正确执行,打印出你所期望的结果“Hello”

[cpp] view plaincopyprint?

  1. static NSMutableArray*array;  
  2.    
  3. -(void)viewDidLoad  
  4. {  
  5.     [super viewDidLoad];  
  6.     array= [[NSMutableArray alloc]initWithCapacity:5];  
  7.     [array release];  
  8.     [array addObject:@"Hello"];//之所以不会crash,是在于事件周期未完,内存回收机制还没有执行,没有真正的回收掉array的对象内存。  
  9.     NSLog(@"%@",[array objectAtIndex:0]);  
  10. }  


但是一旦加上了NSZombieEnable 设置,上面的代码行  [array addObject:@"Hello"] 也将无法投机取巧了,同样会得到错误提示:

*** -[__NSArrayM addObject:]:message sent to deallocated instance 0x6557370

即使该array 所指向的内存还是原来的数据也不能逃脱掉 NSZombieEnable 的法眼。也就是之所以未设置 NSZombieEnable 时上面代码能得到正确结果,是因为,虽然 [array release] 是标记为释放掉该内存块,但是后面使用 array 时,因为该指针指向的内存数据未被覆盖,所以未出错,这和C++ 的指针 delete 后的效果是一样的。


  1. CocoaDev,个人觉得讲Cocoa技术十分专业的网站之一,下面的链接详细讲了讲NSZombieEnable的原理。http://www.cocoadev.com/index.pl?NSZombieEnabled
  2. 苹果官方的Mac OS X Debugging Magic,详细讲述了最为一个高级苹果程序员应该具备的调试技巧 http://developer.apple.com/library/mac/#technotes/tn2004/tn2124.html
  3. 其实还可以在Instruments中开启NSZombie选项,这样就可以在Instruments中直接查看crash时候的callstack了:http://www.markj.net/iphone-memory-debug-nszombie/

最后提醒NSZombieEnabled只能在调试的时候使用,千万不要忘记在产品发布的时候去掉,因为NSZombieEnabled不会真正去释放dealloc对象的内存,一直开启后果可想而知,自重!

http://unmi.cc/nszombieenabled-locate-exc_bad_access-error,来自 隔叶黄莺 Unmi Blog

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to Windows Update prompt Error 0x8024401c error Solution to Windows Update prompt Error 0x8024401c error Jun 08, 2024 pm 12:18 PM

Table of Contents Solution 1 Solution 21. Delete the temporary files of Windows update 2. Repair damaged system files 3. View and modify registry entries 4. Turn off the network card IPv6 5. Run the WindowsUpdateTroubleshooter tool to repair 6. Turn off the firewall and other related anti-virus software. 7. Close the WidowsUpdate service. Solution 3 Solution 4 "0x8024401c" error occurs during Windows update on Huawei computers Symptom Problem Cause Solution Still not solved? Recently, the web server needs to be updated due to system vulnerabilities. After logging in to the server, the update prompts error code 0x8024401c. Solution 1

How to disable background applications in Windows 11_Windows 11 tutorial to disable background applications How to disable background applications in Windows 11_Windows 11 tutorial to disable background applications May 07, 2024 pm 04:20 PM

1. Open settings in Windows 11. You can use Win+I shortcut or any other method. 2. Go to the Apps section and click Apps & Features. 3. Find the application you want to prevent from running in the background. Click the three-dot button and select Advanced Options. 4. Find the [Background Application Permissions] section and select the desired value. By default, Windows 11 sets power optimization mode. It allows Windows to manage how applications work in the background. For example, once you enable battery saver mode to preserve battery, the system will automatically close all apps. 5. Select [Never] to prevent the application from running in the background. Please note that if you notice that the program is not sending you notifications, failing to update data, etc., you can

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

How to convert deepseek pdf How to convert deepseek pdf Feb 19, 2025 pm 05:24 PM

DeepSeek cannot convert files directly to PDF. Depending on the file type, you can use different methods: Common documents (Word, Excel, PowerPoint): Use Microsoft Office, LibreOffice and other software to export as PDF. Image: Save as PDF using image viewer or image processing software. Web pages: Use the browser's "Print into PDF" function or the dedicated web page to PDF tool. Uncommon formats: Find the right converter and convert it to PDF. It is crucial to choose the right tools and develop a plan based on the actual situation.

How to read dbf file in oracle How to read dbf file in oracle May 10, 2024 am 01:27 AM

Oracle can read dbf files through the following steps: create an external table and reference the dbf file; query the external table to retrieve data; import the data into the Oracle table.

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

Interpretation of Botanix: decentralized BTC L2 for network asset management (with interactive tutorial) Interpretation of Botanix: decentralized BTC L2 for network asset management (with interactive tutorial) May 08, 2024 pm 06:40 PM

Yesterday, BotanixLabs announced that it has completed a total of US$11.5 million in financing, with participation from Polychain Capital, Placeholder Capital and others. Financing will be used to build the decentralized EVM equivalent of BTCL2Botanix. Spiderchain combines the ease of use of EVM with the security of Bitcoin. Since the testnet went live in November 2023, there have been more than 200,000 active addresses. Odaily will analyze Botanix’s characteristic mechanism and testnet interaction process in this article. Botanix According to the official definition, Botanix is ​​a decentralized Turing-complete L2EVM built on Bitcoin and consists of two core components: Ethereum Virtual Machine

How to solve access violation error How to solve access violation error May 07, 2024 pm 05:18 PM

Access Violation error is a run-time error that occurs when a program accesses a memory location beyond its memory allocation, causing the program to crash or terminate abnormally. Solutions include: checking array boundaries; using pointers correctly; using appropriate memory allocation functions; freeing freed memory; checking for memory overflows; updating drivers and systems; checking third-party libraries; using a debugger to trace execution; contacting the software vendor for support.

See all articles