【发布时间】:2013-05-14 07:04:36
【问题描述】:
我正在编写一个需要在文件中存储一些持久性信息的应用程序,但我在调试 NSFileManager 的 createFileAtPath:contents:attributes: 函数时遇到了问题,我已将问题简化为以下代码。
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");
}
【问题讨论】:
-
您的测试设备和模拟器中是否都存在此问题,还是仅在其中一个中存在?
-
此时仅在模拟器中,我没有测试设备。虽然我很想知道是否有其他人从上述代码中收到相同的输出。
-
我刚刚运行了代码,它运行良好。第一次通过:“找不到文件,将创建文件”,没有错误。第二次:“文件存在”。
-
谢谢 steve,不知道我到底出了什么问题。
标签: ios objective-c