【问题标题】:NSFileManager:enumeratorAtURL: returns a different form of URL to NSFileManager:URLForDirectoryNSFileManager:enumeratorAtURL: 返回不同形式的 URL 到 NSFileManager:URLForDirectory
【发布时间】:2012-07-17 19:39:35
【问题描述】:

如果我使用 NSFileManager:URLForDirectory 获取沙盒的应用程序支持目录,那么我会返回以下 URL:

file://localhost/var/mobile/Applications/EA80DE91-394C-4EAB-B269-1081C859BB0F/Library/Application%20Support/

但是,如果我使用 NSFileManager:enumeratorAtURL 搜索目录,我会返回表单的 URL:

file://localhost/private/var/mobile/Applications/EA80DE91-394C-4EAB-B269-1081C859BB0F/Library/Application%20Support/

这给我带来了问题,因为我正在执行 URL 搜索/替换操作,而差异会导致不匹配。我之前在其他地方遇到过这种差异,然后我的解决方案是使用 URL 的路径(使用 NSURL:path)而不是原始 URL,但是在这种情况下这不起作用,因为生成的路径是:

/var/mobile/Applications/EA80DE91-394C-4EAB-B269-1081C859BB0F/Library/Application Support
/private/var/mobile/Applications/EA80DE91-394C-4EAB-B269-1081C859BB0F/Library/Application Support/

我要做的是:我的应用程序支持目录中可以有任意数量的文件,名称相同但位置不同,我需要提取相对于应用程序支持目录的路径。即如果我有以下情况

/Application Support/abc/file.dat
/ApplicationSupport/abc/def/file.dat

我希望能够提取“abc”和“abc/def”。我正在使用以下代码执行此操作:

NSArray *keys = [NSArray arrayWithObject:NSURLIsRegularFileKey];
NSDirectoryEnumerator *dirEnumerator = [self.fileManager enumeratorAtURL:[MyManager appSupportDirectory]
                                          includingPropertiesForKeys:keys
                                                             options:NSDirectoryEnumerationSkipsHiddenFiles
                                                        errorHandler:nil];
    for (NSURL *url in dirEnumerator)
    {
        if ( NSOrderedSame == [[url lastPathComponent] caseInsensitiveCompare:kFilename])
        {
            NSString *appSupportPath = [[MyManager appSupportDirectory] path];
            NSString *pathToFile = [url path];
            pathToFile = [pathToFile URLByDeletingLastPathComponent];
            NSString *subPath = [pathToFile  stringByReplacingOccurrencesOfString:appSupportPath withString:@""];

(MyManager:appSupportDirectory 调用 NSFileManager:URLForDirectory: 使用 NSApplicationSupportDirectory)

这在 enumeratorAtURL:URLFOrDirectory: 返回相同路径的模拟器上运行良好,但由于它们在硬件上的差异而失败。

有没有办法让 enumeratorAtURL:URLForDirectory: 返回相同的路径,或者如果没有,是否有另一种优雅的方法可以将子路径提取到我目前正在做的事情?

【问题讨论】:

    标签: ios cocoa-touch nsfilemanager


    【解决方案1】:

    var 符号链接到/private/var/

    调用[url URLByResolvingSymlinksInPath] 修复它。

    更多讨论请参见What does the /private prefix on an iOS file path indicate?

    【讨论】:

      【解决方案2】:

      我不得不改为这样做:

      NSDirectoryEnumerator *dirEnum = [self.fileManager enumeratorAtPath: [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Application Support/"]];
      

      【讨论】:

      • 我遇到了同样的问题。 fileManager 的 contentsOfDirectoryAtURL 返回一个带有 /private/ 的 URL。而且我无法与数据库中的 URL 记录进行比较。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2016-07-13
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2012-02-01
      • 2015-10-08
      相关资源
      最近更新 更多