我有这段代码,当我使用print命令时,可以获得所有提取结果,但是如果我尝试将结果放入UILabel并显示,则仅显示最后插入的值。
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "date") as! String)
print(data.value(forKey: "score") as! String)
var x = data.value(forKey: "date") as! String
var y = data.value(forKey: "score") as! String
//allScores.text = "Session started on \(x), points earned: \(y)"
}
} catch {
print("Failed")
}
做到这一点,
print(data.value(forKey: "date") as! String)
print(data.value(forKey: "score") as! String)
但这不是,它仅显示我的UILabel中最后插入的值
var x = data.value(forKey: "date") as! String
var y = data.value(forKey: "score") as! String
allScores.text = "Session started on \(x), points earned: \(y)"
答案 0 :(得分:1)
尝试这样
do {
let result = try managedContext.fetch(fetchRequest)
allScores.text = ""
for data in result as! [NSManagedObject] {
print(data.value(forKey: "date") as! String)
print(data.value(forKey: "score") as! String)
var x = data.value(forKey: "date") as! String
var y = data.value(forKey: "score") as! String
allScores.text = (allScores.text ?? "") + "Session started on \(x), points earned: \(y)"
}
} catch {
print("Failed")
}