【发布时间】:2013-02-06 05:17:41
【问题描述】:
我的应用在 iPhone 上运行时出现错误,但在模拟器上运行时却没有。我使用主目录路径的长度来提取 /Documents 中文件的相对路径。不幸的是,这并不总是在 iPhone 上正常工作,因为前缀“/private”被添加到主路径中。但是,无论有无前缀,都可以引用同一个文件。下面的代码演示了这种不一致。 “/private”的用途是什么,iOS什么时候提供?
- (IBAction)testHomepath:(id)sender {
NSFileManager *fmgr = [NSFileManager defaultManager];
NSString *homePath = [NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
NSString *dirPath = [homePath stringByAppendingPathComponent:@"TempDir"];
NSURL *dirURL = [NSURL fileURLWithPath:dirPath];
NSString *filePath = [dirPath stringByAppendingPathComponent:@"test.jpg"];
[fmgr createDirectoryAtPath:dirPath withIntermediateDirectories:NO attributes:nil error:nil];
[fmgr createFileAtPath:filePath contents:nil attributes:nil];
NSArray *keys = [[NSArray alloc] initWithObjects:NSURLNameKey,nil];
NSArray *files = [fmgr contentsOfDirectoryAtURL:dirURL includingPropertiesForKeys:keys options:0 error:nil];
NSURL *f1 = (files.count>0)? [files objectAtIndex:0] : 0;
NSURL *f2 = (files.count>1)? [files objectAtIndex:1] : 0;
bool b0 = [fmgr fileExistsAtPath:filePath];
bool b1 = [fmgr fileExistsAtPath:f1.path];
bool b2 = [fmgr fileExistsAtPath:f2.path];
NSLog(@"File exists=%d at path:%@",b0,filePath);
NSLog(@"File exists=%d at path:%@",b1,f1.path);
NSLog(@"File exists=%d at path:%@",b2,f2.path);
}
在 iPhone 上运行时将以下内容写入日志。我手动间隔输出以显示第 1 行和第 2 行之间的差异。
2013-02-20 16:31:26.615 Test1[4059:907] File exists=1 at path: /var/mobile/Applications/558B5D82-ACEB-457D-8A70-E6E00DB3A484/Documents/TempDir/test.jpg
2013-02-20 16:31:26.622 Test1[4059:907] File exists=1 at path:/private/var/mobile/Applications/558B5D82-ACEB-457D-8A70-E6E00DB3A484/Documents/TempDir/test.jpg
2013-02-20 16:31:26.628 Test1[4059:907] File exists=0 at path:(null)
在模拟器上运行时写入日志如下(无“/private”):
2013-02-20 16:50:38.730 Test1[7224:c07] File exists=1 at path:/Users/kenm/Library/Application Support/iPhone Simulator/6.1/Applications/C6FDE177-958C-4BF5-8770-A4D3FBD281F1/Documents/TempDir/test.jpg
2013-02-20 16:50:38.732 Test1[7224:c07] File exists=1 at path:/Users/kenm/Library/Application Support/iPhone Simulator/6.1/Applications/C6FDE177-958C-4BF5-8770-A4D3FBD281F1/Documents/TempDir/.DS_Store
2013-02-20 16:50:38.733 Test1[7224:c07] File exists=1 at path:/Users/kenm/Library/Application Support/iPhone Simulator/6.1/Applications/C6FDE177-958C-4BF5-8770-A4D3FBD281F1/Documents/TempDir/test.jpg
【问题讨论】:
-
你能做的最糟糕的事情就是对你的应用程序的 Documents 目录的路径是什么或将会是什么做出任何假设。期望该路径的特定长度更糟。只需确定文档路径并将其从完整路径中删除即可获取您的相对路径。
-
@maddy,我没有假设特定的长度,只是 /Documents 的路径不会改变,这被 IOS 添加 /private 所违反,因为 Kevin Ballard 在下面指出只是一个符号链接.我来自 Windows,我从未见过这种情况发生。现在,我在 IOS 给我的任何路径中找到 /NSHomeDirectory()/Documents 的子字符串,然后在相对路径之后调用路径字符串。您对此有任何问题或知道获取相对路径的更好方法吗?
-
您的问题是:我使用的是主目录路径的长度。您应该始终使用相对于 Documents 目录的路径。你绝不能坚持完整的路径。如果您只有相对目录,则无需处理任何内容。
-
@maddy,我只保留相对路径,但 NSFileManager contentsOfDirectoryAtURL 返回完整路径。我需要删除 /Documents 之前的内容以获取我可以保留的相对路径。
-
请改用
NSFileManager contentsOfDirectoryAtPath:error:。返回的路径列表与您获取内容的路径有关。