【发布时间】: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