【问题标题】:How do i create a file in the default documents directory in an iOS app如何在 iOS 应用程序的默认文档目录中创建文件
【发布时间】: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


【解决方案1】:
//  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");

【讨论】:

  • 谢谢,这是问题所在,我假设 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] 返回的路径会存在,显然模拟器中并非总是如此。
【解决方案2】:

swift5

guard let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first else {
            preconditionFailure()
}
let path = (docdir as NSString).appendingPathComponent(yourfilename + "." + yourfilenameExtension)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2015-11-25
    • 2019-07-14
    • 2012-03-01
    • 2018-04-13
    • 2013-08-06
    • 2010-12-18
    相关资源
    最近更新 更多