我正在编写一个需要在文件中存储一些持久性信息的应用程序,但我在调试createFileAtPath:contents:attributes:NSFileManager的函数时遇到问题,我已将问题减少到下面的代码段.
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");
}
}
Run Code Online (Sandbox Code Playgroud)
由于该函数没有采用NSError对象,因此我无法找到它返回false的原因.
从我在这里看到的其他示例在iOS上编写文件,在这里如何以设备方式在iOS下使用CoreAudio以编程方式创建一个长度为空的.m4a文件?将nil传递给内容和属性参数应该没问题.我已经尝试指定两个参数并获得相同的结果.
我认为这可能是一个权限问题,但我不确定以下代码是否是检查目录权限的正确方法.
if ([filemgr isWritableFileAtPath:documentsDirectory] == …Run Code Online (Sandbox Code Playgroud)