【问题标题】:NSFileManager leaksNSFileManager 泄漏
【发布时间】:2011-09-18 09:34:41
【问题描述】:

我在我编写的以下 sn-p 代码中发现了内存泄漏

NSFileManager *fileManager=[[NSFileManager alloc] init];
fileList=[[fileManager contentsOfDirectoryAtPath:DOCUMENTS_FOLDER error:nil] retain];
[fileManager release];  

泄露信息——

[NSFileManager contentsOfDirectoryAtPath:error:]
[NSFileManager directoryContentsAtPath:matchingExtension:options:keepExtension:error]
CFStringCreateWithBytes
_CFStringCreateImmutableFunnel3
_CFRuntimeCreateInstance.

我不知道怎么解决?

【问题讨论】:

  • 以后要发布fileList吗?

标签: iphone cocoa-touch cocoa memory-management nsfilemanager


【解决方案1】:

文件管理器的 alloc-then-release 很好。但是

fileList=[[fileManager contentsOfDirectoryAtPath:DOCUMENTS_FOLDER error:nil] retain];

您现在有一个保留的数组。你必须稍后释放它。如果你不这样做,你就会有泄漏。

【讨论】:

    【解决方案2】:

    内存管理的经验法则很简单:

    对于每个alloc、retain、copy 或new,您必须有一个对应的release 或autorelease。

    你在这里调用了retain:

    fileList=[[fileManager contentsOfDirectoryAtPath:DOCUMENTS_FOLDER error:nil] retain];
    

    但你不释放它。

    【讨论】:

    • 如果像这样覆盖此代码:fileList=[fileManager contentsOfDirecotryAtPath:DOCUMENT_FOLDER error:nil];它也泄漏了!怎么办?
    • @scofield:同样的方式。您必须稍后保留或复制它,然后未能发布它。使用 Instruments 的 Leaks 模板(尤其是 Object History 功能)来查看您正在泄漏什么以及如何泄漏。
    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2012-05-04
    相关资源
    最近更新 更多