I am receiving a JSON that I need to parse a couple of times. This json contains file content that could be large if the document is large. Here's a rundown of the code I have and where the memory leak occurs in my code:
Assumption:data received is 30MB.
id retVal;
@autoreleasepool{
NSMutableDictionary *resDict = /*server response*/
/*resDict will increase memory by 30MB as it should*/
NSData *responseData = [resDict valueForKey:@"data"];
resDict = nil;
retVal = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
/*retVal will increase memory by 30MB. I'd imagine because there's two instances of
this file now. Total of 60MB usage.*/
responseData = nil;
/*This does not release the memory as I thought it would*/
NSString *dataString = [retVal valueForKey:@"data"];
retval = nil;
/*This also does not release any memory*/
NSData *actualData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
/*This will add another 30MB. Total of 90MB now.*/
dataString = nil;
/*This immediately replenishes 30MB of memory. Total of 60MB now.*/
retVal = [NSJSONSerialization JSONObjectWithData:actualData options:0 error:nil];
/*This adds 30MB of memory. Total of 90MB now.*/
actualData = nil;
/*This does not release any memory*/
}
return retVal;
The end of the auto release pool will release 30 MB, putting me at a total of 60MB for a 30MB file. Once it exits the function, it will release that extra 30MB's bringing the memory consumption to exactly where I would expect it to be, 30MB for a 30MB file.
The problem I am having is some files are much larger that 30MB's. So in the middle of all that processing I have above, I cannot have the memory consumption being 3 times larger(90MB) than it should be.
Is there something I'm doing wrong that would not be cleaning up the variables I am nullifying? I've tried setting autoreleasepools in areas where I believe cleanup should occur, i.e. one line before resDict is declared, and ends after responseData is nil. I've tried so many different methods, but none seem to work for me. I'm hoping some of you may have some experience in this. Any help is appreciated. Thank you!
Also, I have seen this post on Stack Overflow: iOS Download & Parsing Large JSON responses is causing CFData (store) leaks
It seems similar to mine, but I'm not getting any solutions that work for me from it.