结构数组:如何保存在 coredata 中?

Posted

技术标签:

【中文标题】结构数组:如何保存在 coredata 中?【英文标题】:Array of structs: How to save in coredata? 【发布时间】:2017-06-14 12:09:03 【问题描述】:

我正在尝试将结构数组保存到 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 个搜索结果。每个条目是:age = 0;名字 = 无;姓氏 = 无;

为了比较,这段代码,没有循环是有效的:

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

    


【问题讨论】:

您如何从数组Studentsdata 获得 32 个对象,只有 3 个对象 我不知道。每次我调用该函数时,ißm 都会再获得 4 个搜索结果。 (现年 48 岁)。 Studentdata 中的循环似乎有效,我可以在控制台中看到。问题应该在 fetchrequest 中。 我添加了一个较小版本的代码,它正在工作。这很奇怪,因为从 fetchrequest 开始就一样了。 【参考方案1】:

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

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

【讨论】:

谢谢,看起来不错。建筑物运行没有错误。但是当我打印出“学生”时,数据仍然是空的。 (实体:学生;id:0x340000b ;数据:年龄 = 0; firstName = nil; lastName = nil; ) @JoschHazard 用你当前的代码编辑你的问题,你也没有用fetchRequest 调用fetch 不确定您是否从上面获取我的 cmets:我添加了当前代码。也用于比较正在运行的较小版本。在控制台中,“for-in”功能似乎有效。之后,可能 fetchrequest 不起作用。奇怪,因为它在较小的“工作版本”中是一样的。谢谢【参考方案2】:

如果有人感兴趣,我找到了解决方案: 您首先必须像这样在 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)")

        

    


就是这样。

【讨论】:

这是不需要的,您可以在不需要的任何地方声明结构,例如该结构应该在 coredata 类中,如果您不在该类中声明它,您仍然可以在该类中使用结构。 【参考方案3】:

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

【讨论】:

以上是关于结构数组:如何保存在 coredata 中?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 NSManagedObject 将 NSDictionary 保存到 CoreData?

在 coredata 中保存实体数组

如何在Coredata中存储自定义结构数组[关闭]

将 NSData 数组保存到 CoreData

在CoreData中保存数组的值时,只保存一个值

如何一次将多个关系保存到 CoreData?