在iOS上写入文件

如何在iOS上写入文件?我正在尝试使用下面的代码来做,但是我做错了什么:


char *saves = "abcd";

NSData *data = [[NSData alloc] initWithBytes:saves length:4]; 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

[data writeToFile:appFile atomically:YES];

我在资源上创建了MyFile.txt。


慕娘9325324
浏览 725回答 3
3回答

白衣染霜花

您的代码正在我的末端运行,我已经对其进行了测试。您在哪里查看更改?使用文档目录路径。获取路径-NSLog(@"%@",documentsDirectory);并从控制台复制路径,然后打开finder并按Cmd + shift + g并在此处粘贴路径,然后打开文件

PIPIONE

迅速func saveFile() {    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)    let documentsDirectory = paths[0] as! String    let fileName = "\(documentsDirectory)/textFile.txt"    let content = "Hello World"    content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding, error: nil)}func loadFile() {    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)    let documentsDirectory = paths[0] as! String    let fileName = "\(documentsDirectory)/textFile.txt"    let content: String = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: nil)!    println(content)}迅捷2func saveFile() {    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)    let documentsDirectory = paths[0]    let fileName = "\(documentsDirectory)/textFile.txt"    let content = "Hello World"    do{        try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)    }catch _ {    }}func loadFile()->String {    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)    let documentsDirectory = paths[0]     let fileName = "\(documentsDirectory)/textFile.txt"    let content: String    do{       content = try String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding)    }catch _{        content=""    }    return content;}迅捷3func saveFile() {    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)    let documentsDirectory = paths[0]    let fileName = "\(documentsDirectory)/textFile.txt"    let content = "Hello World"    do{        try content.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)    }catch _ {    }}func loadFile()->String {    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)    let documentsDirectory = paths[0]    let fileName = "\(documentsDirectory)/textFile.txt"    let content: String    do{        content = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8)    } catch _{        content=""    }    return content;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS