【问题标题】:NSFileManager - URLsForDirectory... or URLForDirectoryNSFileManager - URLsForDirectory... 或 URLForDirectory
【发布时间】:2012-12-08 14:49:32
【问题描述】:

-[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] 需要一个 NSSearchPathDomainMask 并返回一个 URL。 (...appropriateForURL:create:error: 部分在文档中有点混乱。)

-[NSFileManager URLsForDirectory:inDomains:] 允许您为 domain 参数创建位掩码并返回 URL 数组。

在我看来,这两种方法之间存在重叠。如果我的目标是从 iOS 应用的沙箱中获取 Documents、Library 或 etc 目录,我应该什么时候使用一个而不是另一个?

【问题讨论】:

    标签: ios nsfilemanager


    【解决方案1】:

    访问 Documents 目录(或其他类似目录)的标准方法是如下代码:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    

    这类似于做:

    NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    NSURL *documentsURL = URLs[0];
    

    主要区别在于第一个为您提供NSString 的路径,而第二个为您提供NSURL 的路径。

    可以通过以下方式使用其他方法:

    NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    

    您可以为 Documents 目录传递NO,因为它始终存在。您应该将YES 传递给应用程序支持目录,因为它默认不存在。理想情况下,您不应该将 nil 传递给错误,这样您就可以看到如果方法调用返回 nil 会发生什么。

    这三种方法中的任何一种都有效。如果要将路径作为字符串,请使用第一个。如果您想将其用作 URL,请使用第 3 个。如果您很少需要传入多个域,请使用第二个。

    【讨论】:

    • 来自 Apple 的文档:You should consider using the NSFileManager methods URLsForDirectory:inDomains: and URLForDirectory:inDomain:appropriateForURL:create:error:. which return URLs, which are the preferred format.
    • 如果你想要 URL,那是真的。如果您希望路径为 NSString,那么我发布的内容很好。
    • 请注意,从 [[NSFileManager defaultManager] 获取的默认 NSFileManager 不是线程安全的。因此,如果您在多个队列(线程)中执行读/写操作,请使用它的一个实例。 [[NSFileManager alloc] 初始化]
    • @Hulvej 来自NSFileManager 的文档:The methods of the shared NSFileManager object can be called from multiple threads safely.。如果您需要使用 NSFileManagerDelegate 方法,建议创建您自己的 NSFileManager 实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2012-03-28
    • 2011-09-18
    • 2011-06-22
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多