结构数组:如何保存coredata?

时间:2017-06-14 12:09:03

标签: arrays swift core-data struct nsdictionary

我正在尝试将一组结构保存到coredata中。我做了很多研究,但我找不到解决方案。 这就是我所拥有的:

import Cocoa
import CoreData

class ViewController: NSViewController {

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


    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()

        let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student


        for items in Studentsdata {
            student.firstName = StudentsStruct.firstName
            student.lastName = StudentsStruct.lastName
            student.age = StudentsStruct.age
        }

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

        print (student)
    }
}

DatabaseController是我从本教程获得的解决方案: https://www.youtube.com/watch?v=da6W7wDh0Dw 它不是那么重要,它只是制作“getContext”函数。 重要的是,在命令行“student.firstName = StudentsStruct.firstName”我得到错误“实例成员”firstName“不能用于类型ViewController.StudentStruct。 经过尝试和尝试,我已经没有想法如何将结构数组放入coredata。

这是DatabaseController文件:

import Foundation
import  CoreData


class DatabaseController  {

    private init() {
    }
    class func getContext() -> NSManagedObjectContext {
        return DatabaseController.persistentContainer.viewContext
    }

    // MARK: - Core Data stack

    static var persistentContainer: NSPersistentContainer = {
                let container = NSPersistentContainer(name: "StudentCoreFile")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {
                               fatalError("Unresolved error \(error)")
            }
        })
        return container
    }()

    class func saveContext () {
        let context = DatabaseController.persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

提前感谢任何帮助!

好的,你是对的,我忘了执行fetchrequest。这是我目前的代码:

import Cocoa
import CoreData

class ViewController: NSViewController {

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


    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()

        let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student


        for item in Studentsdata {
            let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student
            student.firstName = item.firstName
            student.lastName = item.lastName
            student.age = Int16(item.age)
        }
        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)
            }

        } catch {

            print ("error")

        }

    }
}

它没有错误地运行。现在我得到32个搜索结果。每个条目是:年龄= 0; firstName = nil; lastName = nil;

为了比较,没有循环的这段代码正在运行:

import Cocoa
import CoreData

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student

        student.firstName = "henry"
        student.lastName = "miller"
        student.age = 22

        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)
            }
        } catch {

            print ("error")
        }

    }

}

3 个答案:

答案 0 :(得分:3)

您需要访问for循环中的item,并且您当前正在for循环中访问相同的对象Student对象,而不是每次都需要创建一个新的Student for循环的迭代。

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()

答案 1 :(得分:3)

如果有人有兴趣,我找到了解决方案: 首先必须在CoredataEntity类中设置结构,如:

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

}

然后使用相同的结构来粘贴数据:

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

        }

    }

}

多数民众赞成。

答案 2 :(得分:0)

也许这很懒。您也可以将数组编码为json对象,然后在NSManagedObject上为其创建一个可转换的字段。当您要检索时,只需解码并向下转换为正确的类型。这就是我在一个项目中所做的;工作正常。