首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ARC下的EXC_BAD_ACCESS内存错误

ARC下的EXC_BAD_ACCESS内存错误
EN

Stack Overflow用户
提问于 2012-08-05 12:10:15
回答 2查看 544关注 0票数 0

在下面的方法中,我在包含"urlString“变量的行上收到了"EXC_BAD_ACCESS”。我的研究表明,当程序向已经释放的变量发送消息时,就会发生此错误。但是,由于我使用的是ARC,所以我不会手动释放内存。如何防止ARC过早释放此变量?

代码语言:javascript
运行
复制
-(NSMutableArray *)fetchImages:(NSInteger *)count {
//prepare URL request
NSString *urlString = [NSString stringWithFormat:@"http://foo.example.com/image?quantity=%@", count];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

//Perform request and get JSON as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

//Parse the retrieved JSON to an NSArray
NSError *jsonParsingError = nil;
NSArray *imageFileData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];

//Create an Array to store image names

NSMutableArray *imageFileNameArray;

//Iterate through the data
for(int i=0; i<[imageFileData count];i++)
{
    [imageFileNameArray addObject:[imageFileData objectAtIndex:i]];

}

return imageFileNameArray;

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-05 12:12:29

你的问题与ARC无关。NSInteger不是一个类,所以您不希望使用%@格式。%@将向系统认为是对象的对象发送description方法,但当它被证明不是one - CRASH时。要解决您的问题,您有两个选择:

您可能需要的

stringWithFormat:@"http://foo.example.com/image?quantity=%d",* NSString = NSString urlString*计数;

首先确保count指针有效!

  • 您可能需要将方法签名更改为:

-(NSMutableArray *)fetchImages:(NSInteger)计数;

然后更改urlString行,如下所示:

NSString * stringWithFormat:@"http://foo.example.com/image?quantity=%d",= NSString urlString计数;

您还需要修复所有调用者以匹配新签名。

第二种选择对我来说似乎更“正常”,但如果没有更多你的程序,就不可能更具体。

票数 6
EN

Stack Overflow用户

发布于 2012-08-05 16:06:32

您可能还想分配和初始化

代码语言:javascript
运行
复制
NSMutableArray *imageFileNameArray;

在添加对象到它之前,否则你会一直崩溃。所以你就会有

代码语言:javascript
运行
复制
//Create an Array to store image names

NSMutableArray *imageFileNameArray = [[NSMutableArray alloc] init];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11813901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档