更新时间:2023-01-15 18:06:27
我建议使用更有效的方法来查找以 iD 加逗号
开头的行.根据代码,第 7 个字段是 bagged
,第 8 个字段是 baggedDate
.
I recommend to use a more efficient way to find the line starting with iD plus comma
. And according to the code the 7th field is bagged
and the 8th field is baggedDate
.
因此将更改直接写入 attributes
数组,重新加入它,将字符串重新分配给给定索引处的 lines
数组并加入 lines
> 带有 CRLF 分隔符的数组.最后将字符串写回磁盘
So write the changes directly into the attributes
array, rejoin it, reassign the string to the lines
array at given index and join the lines
array with CRLF separator. Finally write the string back to disk
func saveToFile(bagged: Int, iD: Int, dateBagged: Date){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dateBaggedFormatted = dateFormatter.string(from: dateBagged)
do {
let file = "file.txt"
let dir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURL = dir.appendingPathComponent(file)
let text = try String(contentsOf: fileURL, encoding: .utf8)
var lines = text.components(separatedBy: .newlines)
if let index = lines.firstIndex(where: {$0.hasPrefix("\(iD),")}) {
var attributes = lines[index].components(separatedBy: ",")
attributes[6] = String(bagged)
attributes[7] = dateBaggedFormatted
lines[index] = attributes.joined(separator: ",")
let result = lines.joined(separator: "\r\n")
try result.write(to: fileURL, atomically: true, encoding: .utf8)
}
} catch {print(error)}
}