如何解决iphone开发中遇到的EXC_BAD_ACCESS错误 [英] How do i resolve EXC_BAD_ACCESS errors encountered in iphone development

查看:309
本文介绍了如何解决iphone开发中遇到的EXC_BAD_ACCESS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一件简单的事;从互联网上读取图像,将其保存到iphone上的应用程序文档目录中,然后从该文件中读回来,以便我以后可以用它做其他事情。编写文件工作正常,但当我尝试读回来时,我在GDB中得到一个EXC_BAD_ACCESS错误,我不知道如何解决。这是我的代码基本上是这样的:

I'm trying to do a simple thing; read an image from the internet, save it to the app's documents directory on the iphone, and read it back from that file so that i can do other things with it later. Writing the file works fine but when i try to read it back i get an EXC_BAD_ACCESS error in GDB that i have no idea how to resolve. Here is what my code basically looks like:

-(UIImage *) downloadImageToFile {
NSURL * url = [[NSURL alloc] initWithString: self.urlField.text];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

[paths release]
NSString * path = [documentsDirectory stringByAppendingString:@"/testimg.png"];

NSData * data = [[NSData alloc] initWithContentsOfURL:url];

[data writeToFile:path atomically:YES];

return [[UIImage alloc] initWithContentsOfFile:path];
}

当我尝试初始化UIImage时,代码在return语句中失败文件。有什么想法吗?

The code fails in the return statement when i try to initialize the UIImage from the file. Any ideas?

编辑:忽略添加最初代码中存在问题的版本。

Edit: neglected to add a release that was the problem in the code originally.

推荐答案

您的代码显示对Objective-C中内存管理的工作方式缺乏了解。除了您收到的EXC_BAD_ACCESS错误之外,不正确的内存管理还会导致内存泄漏,在iPhone等小型设备上可能会导致随机崩溃。

Your code shows a severe lack of knowledge of how memory management works in Objective-C. In addition to the EXC_BAD_ACCESS errors you're receiving, improper memory management also causes memory leaks which, on a small device like the iPhone, can lead to random crashes.

I建议你给这个读一个钍:

I recommend you give this a thorogh read:

Cocoa内存管理编程指南简介

这篇关于如何解决iphone开发中遇到的EXC_BAD_ACCESS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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