【问题标题】:Memory leak if load from NSCachesDirectory如果从 NSCachesDirectory 加载内存泄漏
【发布时间】:2012-10-01 20:22:49
【问题描述】:

我从 plist 加载了很多注释,所有加载都很好,但是如果我从 NSCachesDirectory 内存泄漏工具加载,则会显示泄漏。如果我从 url 加载,则不会泄漏。我在项目中使用 ARC。

内存泄漏

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:@"test.plist"];
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path]; // leaking here

没有泄漏

NSString *urlStr = [[NSString alloc] 
                    initWithFormat:@"http://www.domain.com/test.plist" ];

NSURL *url = [NSURL URLWithString:urlStr];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfURL:url];

【问题讨论】:

  • 其实,我现在看到你已经问过这个问题了,而且这个问题实际上有更多的数据。请不要只是重新提出问题,尤其是在上下文/信息少得多的情况下。

标签: iphone ios xcode memory-leaks automatic-ref-counting


【解决方案1】:

我不确定为什么仪器会显示一个泄漏而不是另一个泄漏,但这几乎可以肯定是由于这些代码 sn-ps 未表示的某些问题。您可以通过简单地使用 URL 方法来验证这一点(无论如何,这是建议的方法,更喜欢使用文件 URL 而不是带有新代码的路径)来定位文件:

NSError* error = nil;
NSURL* fileURL = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error] URLByAppendingPathComponent:@"test.plist"];
if( !fileURL ) { /* deal with error */ }
// If this still leaks, it's due to the way your code is structured and
// you will have to provide more details.
NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfURL:fileURL];

【讨论】:

  • @PavelKaljunen 这意味着它是您代码中的其他内容,您需要发布更多上下文。在 ARC 中生成实际泄漏比在托管内存代码中要困难得多。真正做到这一点的唯一方法是使用孤立的强循环。您需要使用更多信息/详细信息编辑您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-27
  • 2016-08-10
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多