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.
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 theNSStringyou’re allocating.Do it like this:
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.