【问题标题】:Do I want to use NSString filePaths or NSURLs?我想使用 NSString filePaths 还是 NSURLs?
【发布时间】:2012-07-18 23:08:01
【问题描述】:

很多类都有使用 NSStrings 作为 filePath 或 NSURLs 的版本。一个例子:

- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error
- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error

是否存在 /explicit/ 偏好使用其中一个而不是另一个?我正在寻找有关该主题的文档中的注释。

【问题讨论】:

    标签: iphone ios


    【解决方案1】:

    这完全取决于你。但是有很多东西只使用URL。

    您可以轻松地从 NSURL 转到路径。但往另一个方向发展则需要一些规范化。

    例如使用带有方案的路径会给你一个不正确的 url。

    NSString *pathString = @"file://localhost/etc..../Document.txt";
    NSURL *fileURL = [NSURL fileURLWithPath:pathString];// This will not work.
    

    但是,如果初始化正确,您可以期望来自 URL 的路径是正确的路径。

    NSURL *fileURL = [NSURL URLWithString:pathString];
    NSURL *sanePath = fileURL.path;
    

    因此您可以通过 3 个步骤获得正确的网址

    NSURL *fileURL = [NSURL URLWithString:pathString];
    NSURL *sanePath = fileURL.path;
    
    // You can at this point use the Path and expect it will be correct.
    
    fileURL = [NSURL fileURLWithPath:sanePath];
    
    // You can at this point use fileURL and know it will be a correct fileURL with file://.
    

    或者,您可以检查该方案以查看其是否正确。但这是我在使用 AVAsset 时遇到的一个问题,因为它不会单独从路径加载 NSURL。它必须是一个文件URL

    祝你好运。 :)

    【讨论】:

      【解决方案2】:

      This post:

      "通常对于路径相关的操作,您应该更喜欢 NSURL NSString 因为可以更有效地存储路径信息 在 NSURL 中(根据 NSFileManager 的类参考)。所以我 建议您也为您的 API 使用 NSURL。

      NSURL 也有 URLByAppendingPathComponent: 和 URLByAppendingPathExtension:所以也很方便”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 2016-03-09
        • 2011-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多