Search code examples
swiftxcodecore-datauilabel

Why can't I get all my core data fetch results into a UILabel?


I have this code, when I use print command, I can get all of my fetch results, but if I tried to put the results inside a UILabel and display it, only the lasted inserted value shows.

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

Doing this works,

print(data.value(forKey: "date") as! String)
            print(data.value(forKey: "score") as! String)

but this doesn't it only shows last inserted value in my 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)"

Solution

  • try like this

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