In the method below I’m receiving “EXC_BAD_ACCESS” on the line containing the “urlString” variable. My research suggests that this error occurs when the program sends a message to a variable that has already been released. However since I’m using ARC I’m not manually releasing memory. How can I prevent ARC from releasing this variable too soon?
-(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;
}
Your problem has nothing to do with ARC.
NSIntegerisn’t a class, so you don’t want to be using the%@format.%@is going to send adescriptionmethod to what the system thinks is an object, but when it turns out not to be one – CRASH. To solve your problem, you have two options:You might want:
Make sure the
countpointer is valid first!You might need to change your method signature to be:
and then change the
urlStringline as follows:You’ll also need to fix all of the callers to match the new signature.
The second option seems more “normal” to me, but without more of your program it’s impossible to be more specific.