我在iPhone设备上使用NSFileManager创建目录和文件时遇到问题。 我的代码,如下所示,在模拟器上工作正常,但在设备上没有,你能帮我吗?给我一些问题的方向,感谢每一个回复..
我首先以这种方式创建目录:
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *arPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *appPath = [[NSString alloc] init];
appPath = [arPaths objectAtIndex:0];
strDownloadsDir = [[NSString alloc] init];
strDownloadsDir = [[appPath stringByAppendingPathComponent:@"/Other"] copy];
if(![fileMgr fileExistsAtPath:strDownloadsDir])
[fileMgr createDirectoryAtPath:strDownloadsDir attributes:nil];
然后我试图以这种方式在这个目录中创建新文件:
NSString *filePath = [strDownloadsDir stringByAppendingPathComponent:strDlFileName];
//Test whether this file exists, if not, create it
NSLog(@"%@", filePath);
if(![fileMgr fileExistsAtPath:filePath])
{
if([fileMgr createFileAtPath:filePath contents:nil attributes:nil])
NSLog(@"Creating new file at path %@", filePath);
else
NSLog(@"Failed to create new file.");
}
整个NSFileManager似乎有问题,因为当我使用带有此路径的文件的fileExistAtPath时
NSArray *arPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *appPath = [[NSString alloc] init];
appPath = [arPaths objectAtIndex:0];
它也不起作用,我试图将目录更改为NSDocumentsDirectory但它没有帮助
答案 0 :(得分:1)
可能是因为使用方法“createDirectoryAtPath:attrubutes:”被苹果公司拒绝了.....
答案 1 :(得分:0)
您只能在应用程序的沙箱目录下创建文件。 Apple不允许您创建文件。
这是你手机失败的原因吗?
答案 2 :(得分:0)
[[NSFileManager defaultManager] createDirectoryAtPath:strPath withIntermediateDirectories:YES attributes:nil error:nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strFile = [documentsDirectory stringByAppendingPathComponent:@"hello/config.plist"];
NSLog(@"strFile: %@", strFile);
NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"hello"];
if (![[NSFileManager defaultManager] fileExistsAtPath:strPath]) {
NSLog(@"there is no Directory: %@",strPath);
[[NSFileManager defaultManager] createDirectoryAtPath:strPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSArray *keys = [NSArray arrayWithObjects: @"username", @"password", @"serverName", @"serverPort", @"autoSave", nil];
NSArray *values = [NSArray arrayWithObjects: @"11", @"11", @"11", @"11", @"11", nil];
NSDictionary *configInfo = [[NSDictionary alloc] initWithObjects: values forKeys:keys];
if (![configInfo writeToFile: strFile atomically: YES]) {
NSLog(@"write file error");
}