0

I am trying to figure out why I am getting EXC_BAD_ACESS by this code. I have no clu. Can anyone help me pls.

- (void)loadJsonFile:(NSString*)fileName {
    NSError *error = nil;
    NSData *jsonData = [[[NSString alloc]
                         initWithContentsOfFile:[[NSBundle mainBundle]
                                                 pathForResource:fileName ofType:@"json"]
                         encoding:NSUTF8StringEncoding error:&error]
                        dataUsingEncoding:NSUTF8StringEncoding];
    
    jsonDic = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error] retain];
   [jsonData release];
}

If I am commenting out the "[jsonData release];" line, everything functions. But why ? I allocate jsonData, fill it with data and pass it to NSJSONSerialization for getting the jsonDic. After I have the serialization, I release the jsonData and want to use the jsonDic, however some time after the "[jsonData release];" I am getting "EXC_BAD_ACCESS" Exception.

I have no clu, any help appreciated.

Nayan
  • 3,014
  • 2
  • 17
  • 33
i-developer
  • 441
  • 4
  • 12

1 Answers1

2

You release jsonData, but you never retained it. The static analyzer (Menu "Product" ➞ "Analyze") would have shown you this problem. Also, you're not releasing the NSString you're allocating.

Do it like this:

- (void)loadJsonFile:(NSString*)fileName {
    NSError *error = nil;
    NSData *jsonData = [[[[[NSString alloc]
                         initWithContentsOfFile:[[NSBundle mainBundle]
                                                 pathForResource:fileName ofType:@"json"]
                         encoding:NSUTF8StringEncoding error:&error] autorelease]
                        dataUsingEncoding:NSUTF8StringEncoding] retain];

    jsonDic = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error] retain];
    [jsonData release];
}

You might want to consider using ARC (Automatic Reference Counting). Xcode can convert your project almost completely automatically with Menu "Edit" ➞ "Refactor" ➞ "Convert to Objective-C ARC…". There are only few reasons to keep managing memory manually.

Andreas Ley
  • 9,109
  • 1
  • 47
  • 57
  • Thx a lot. I realized now a) I am creating a string object that I never release b) I am releasing the Data Object that I did not own. – i-developer Aug 13 '12 at 12:43
  • What version of XCode are you using? I am using 3.2.5 and I don't see ARC... in any menu... – user574771 Aug 15 '12 at 21:00