ARC下的EXC_BAD_ACCESS内存错误

hug*_*dan 0 objective-c ios

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

-(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;

}
Run Code Online (Sandbox Code Playgroud)

Car*_*rum 6

你的问题与ARC无关. NSInteger不是一个类,所以你不想使用该%@格式. %@将发送一个description方法,系统认为是一个对象,但是当它结果不是一个 - CRASH.要解决您的问题,您有两种选择:

  1. 你可能想要:

    NSString *urlString = 
      [NSString stringWithFormat:@"http://foo.example.com/image?quantity=%d",
            *count];
    
    Run Code Online (Sandbox Code Playgroud)

    确保count指针首先有效!

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

    -(NSMutableArray *)fetchImages:(NSInteger)count;
    
    Run Code Online (Sandbox Code Playgroud)

    然后urlString按如下方式更改行:

    NSString *urlString = 
      [NSString stringWithFormat:@"http://foo.example.com/image?quantity=%d", 
          count];
    
    Run Code Online (Sandbox Code Playgroud)

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

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

  • @hughesdan,几乎所有格式字符串都与`printf`相同.它只是为了使用对象而添加的'%@`. (2认同)