arrays - 结构体数组 : How to save in coredata?

标签 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 中。

这是数据库 Controller 文件:

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;名字 = nil;姓氏 = 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")
        }

    }

}

最佳答案

您需要访问item在您的 for 循环中,您当前也正在访问同一对象 Student for 循环中的对象而不是您需要创建一个新的 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()

关于arrays - 结构体数组 : How to save in coredata?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45762938/

相关文章:

ios - CoreData 临时关系示例

javascript - 我正在尝试使用包含我添加到用户数组的新用户对象的内联数组调用 displayUsers

c++ - 拆分一个句子,以便将每个单词添加到一个数组项中

c++ - 在 C++ 中对指针数组进行排序

ios - 修改核心数据模型每次都需要新版本?

ios - NSFetchedResultsController:排序描述符和部分

C# 将文本框中的字符复制到字节数组

swift - 将屏幕坐标转换为 Metal 的规范化设备坐标

ios - 以编程方式将 UIScrollView 滚动到 Swift 中子 UIView( subview )的顶部

ios - 使用滑动手势在标签栏之间导航