Array of structs: How to save in coredata?

限于喜欢 提交于 2019-12-01 13:06:21

You need to access the item in your for loop also you are currently accessing the same object Student object in for loop instead of that you need to create a new Student in every iteration of for loop.

for item in Studentsdata {
    //Create new student in for loop
    let student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student
    //To get firstName, lastName and age access the item
    student.firstName = item.firstName
    student.lastName = item.lastName
    student.age = item.age
}
//Save context now
DatabaseController.saveContext()
Josch Hazard

In case someone is interested, I found the solution: You first have to set up the struct in the CoredataEntity Class like that:

import Foundation
import CoreData

struct StudentsStruct {
    let firstName: String
    let lastName: String
    let age: Int
}

@objc(Student)
public class Student: NSManagedObject {

    @NSManaged public var firstName: String?
    @NSManaged public var lastName: String?
    @NSManaged public var age: Int16


    var allAtributes : StudentsStruct {
        get {
            return StudentsStruct(firstName: self.firstName!, lastName: self.lastName!, age: Int(self.age))
        }
        set {
            self.firstName = newValue.firstName
            self.lastName = newValue.lastName
            self.age = Int16(newValue.age)
        }
    }

}

Then use the same struct to paste the data:

import Cocoa
import CoreData

class ViewController: NSViewController {

    let studentsdata: [StudentsStruct] = [StudentsStruct(firstName: "Albert", lastName: "Miller", age: 24), StudentsStruct(firstName: "Susan", lastName: "Gordon", age: 24), StudentsStruct(firstName: "Henry", lastName: "Colbert", age: 24)]

    override func viewDidLoad() {
        super.viewDidLoad()

        for items in studentsdata {
            let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student

                       student.allAtributes = items
        }

        DatabaseController.saveContext()

        let fetchRequest: NSFetchRequest<Student> = Student.fetchRequest()

        do {
            let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
            print("number of results: \(searchResults.count)")
            for result in searchResults as [Student] {
                print("student: \(firstName), \(lastName), \(age)" )
            }

        } catch {

            print ("error: \(error)")

        }

    }

}

Thats it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!