2013-05-19 176 views
0

我正在编写需要在文件中存储一些持久性信息的应用程序,但我在调试createFileAtPath时遇到了问题:contents:attributes:NSFileManager的函数,我已将问题简化为下面的一段代码。如何在iOS应用程序的默认文档目录中创建文件

NSFileManager *filemgr; 
filemgr = [NSFileManager defaultManager]; 
NSString * fileName = @"newfile.txt"; 

NSArray *paths = NSSearchPathForDirectoriesInDomains 
(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSString *filePath = [documentsDirectory stringByAppendingPathComponent: fileName]; 
NSLog(@"full path name: %@", filePath); 

// check if file exists 
if ([filemgr fileExistsAtPath: filePath] == YES){ 
    NSLog(@"File exists"); 

}else { 
    NSLog (@"File not found, file will be created"); 
    if (![filemgr createFileAtPath:filePath contents:nil attributes:nil]){ 
     NSLog(@"Create file returned NO"); 
    } 
} 

由于该函数不需要一个NSError对象,我很难找出为什么它返回false。

从我在这里看到的其他例子Write a file on iOS和这里How to programmatically create an empty .m4a file of a certain length under iOS using CoreAudio on device?应该可以将nil传递给内容和属性参数。我试着指定两个参数并收到相同的结果。

我在想这可能是一个权限问题,但我不确定下面的代码是否是检查目录权限的正确方法。

if ([filemgr isWritableFileAtPath:documentsDirectory] == YES){ 
    NSLog (@"File is readable and writable"); 
} 
+0

你,或仅在一个或另一个有两个您的测试设备,并在模拟器这个问题? –

+0

只有在此时的模拟器中,我没有测试设备。虽然我很想知道是否有人从上面的代码中接收到相同的输出。 –

+1

我刚刚运行代码,它完美地工作。第一次通过:“文件未找到,文件将被创建”,没有错误。第二次:“文件存在”。 –

回答

5
// Following Code will create Directory in DocumentsDirectory 

NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
NSString *dirName = [docDir stringByAppendingPathComponent:@"MyDir"]; 

BOOL isDir 
NSFileManager *fm = [NSFileManager defaultManager]; 
if(![fm fileExistsAtPath:dirName isDirectory:&isDir]) 
{ 
    if([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil]) 
     NSLog(@"Directory Created"); 
    else 
     NSLog(@"Directory Creation Failed"); 
} 
else 
    NSLog(@"Directory Already Exist"); 
+0

谢谢,这是问题,我认为由NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0]返回的路径将存在,显然这并非总是在模拟器中。 –

相关问题