gpt4 book ai didi

ios - swift (IOS): Saving and Reading Data into/from a file

转载 作者:行者123 更新时间:2023-11-30 13:49:27 25 4
gpt4 key购买 nike

我正在尝试将数据保存到 Swift 中的 txt 文件中。但到目前为止我还没有成功做到这一点。我正在使用此处已发布的代码,但我不知道我做错了什么。

我将此代码附加到按钮操作,因此当我按下按钮时它应该起作用:

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent(file);

//writing
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}

//reading
do {
let text2 = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}

我有一些不明白的事情,比如文件 file.txt 在哪里,如果不存在,程序会创建它吗?

最佳答案

它实际上位于 xcode 项目目录中,即您必须将文件 file.txt 移动到您的 Xcode 项目(使用拖放并选中“如有必要,复制文件”)。

关于ios - swift (IOS): Saving and Reading Data into/from a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34477021/

25 4 0
文章推荐: swift - 解析错误代码 151
文章推荐: ios - 根据条件设置rootViewController
文章推荐: swift - 在 Swift 中将文本或数据 append 到文本文件
文章推荐: swift - 使用 Realm 关系列表 UITableView