1

我正在编写一个需要在文件中存储一些持久性信息的应用程序,但我在调试 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 对象,因此我无法找出它返回错误的确切原因。

从我在此处看到的其他示例Write a file on iOS和此处How to programmatically create a empty.m4a file of a specific length under iOS using CoreAudio on device? 将 nil 传递给 content 和 attributes 参数应该是可以的。我尝试指定两个参数并收到相同的结果。

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

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

2 回答 2

6
//  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");
于 2013-05-20T04:05:50.047 回答
1

斯威夫特5

guard let docdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first else {
            preconditionFailure()
}
let path = (docdir as NSString).appendingPathComponent(yourfilename + "." + yourfilenameExtension)
于 2019-07-16T07:53:21.800 回答