如果从NSCachesDirectory加载,则内存泄漏

时间:2012-10-01 20:22:49

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

我从plist加载了很多注释,所有加载都很好,但是如果我从NSCachesDirectory加载内存泄漏工具给我看一个泄漏。如果我从网址加载,没有泄漏。我在项目中使用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];

1 个答案:

答案 0 :(得分:0)

我不确定为什么乐器会显示泄漏而不是另一个,但几乎可以肯定是由于某些问题没有被这些代码片段所代表。您可以通过简单地使用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];