hughesdan
hughesdan

Reputation: 2851

EXC_BAD_ACCESS memory error under ARC

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;

}

Upvotes: 0

Views: 555

Answers (2)

dade
dade

Reputation: 188

you also may want to alloc and init the

NSMutableArray *imageFileNameArray;

before adding objects to it, otherwise you'll keep crashing. So you'd have

//Create an Array to store image names

NSMutableArray *imageFileNameArray = [[NSMutableArray alloc] init];

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224864

Your problem has nothing to do with ARC. NSInteger isn't a class, so you don't want to be using the %@ format. %@ is going to send a description method 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:

  1. You might want:

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

    Make sure the count pointer is valid first!

  2. You might need to change your method signature to be:

    -(NSMutableArray *)fetchImages:(NSInteger)count;
    

    and then change the urlString line as follows:

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

    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.

Upvotes: 6

Related Questions