为什么不能将所有核心数据获取结果放入UILabel?

时间:2019-11-23 08:52:04

标签: swift xcode core-data uilabel core

我有这段代码,当我使用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)"

1 个答案:

答案 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")
    }