我的应用在iPhone上运行时出现错误,但在模拟器上运行时没有问题。我使用主目录路径的长度来提取/Documents文件夹中文件的相对路径。不幸的是,在iPhone上这种方法并不总是正确的,因为主目录路径前缀会添加 "/private"。然而,不管有无前缀,都可以正确引用同一个文件。以下代码演示了这种不一致性。iOS何时会提供 "/private" 前缀?
- (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 上运行时写入日志的内容。我手动添加了空格以显示第一行和第二行之间的差异。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
NSFileManager contentsOfDirectoryAtPath:error:
代替。返回的路径列表是相对于您获取内容的路径的。 - rmaddy