NSFileManager:enumeratorAtURL:返回的URL形式和NSFileManager:URLForDirectory不同。

11

如果我使用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:返回相同的路径?如果没有,那么有没有其他优雅的方法来提取子路径以替代我当前的操作?

2个回答

8

3

我不得不改为做这个:

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

我曾经遇到过同样的问题。fileManager 的 contentsOfDirectoryAtURL 返回一个带有 /private/ 的 URL。我在将其与数据库中的 URL 记录进行比较时遇到了麻烦。 - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接