使用NSJSONSerlialization JSONObjectWithData时内存泄漏

时间:2015-03-27 16:53:25

标签: ios objective-c json memory-management memory-leaks

我收到的JSON需要解析几次。如果文档很大,此json包含的文件内容可能很大。这是我的代码的简要说明以及我的代码中发生内存泄漏的地方:

假设:收到的数据是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;

自动发布池的末尾将释放30 MB,对于30 MB文件,总共为60 MB。一旦它退出该功能,它将释放额外的30MB,使内存消耗达到我预期的水平,30MB文件为30MB。

我遇到的问题是有些文件比30MB大得多。因此,在我上面所有处理的中间,我不能让内存消耗比它应该大3倍(90MB)。

我做错了什么,不会清理我无效的变量?我已经尝试在我认为应该进行清理的区域设置autoreleasepool,即在声明resDict之前一行,并在responseData为nil之后结束。我尝试了很多不同的方法,但似乎没有一种方法适合我。我希望你们中的一些人可能有一些这方面的经验。任何帮助表示赞赏。谢谢!

另外,我在Stack Overflow上看过这篇文章:   iOS Download & Parsing Large JSON responses is causing CFData (store) leaks

它似乎与我的相似,但我没有得到任何适用于我的解决方案。

0 个答案:

没有答案