结构数组:如何保存在coredata中? [英] Array of structs: How to save in coredata?

查看:80
本文介绍了结构数组:如何保存在coredata中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I´m trying to save an array of structs into coredata. I did a lot of research, but i cannot find the solution. Here´s what i´ve got:

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的想法.

The DatabaseController is solution i´ve got from this tutorial: https://www.youtube.com/watch?v=da6W7wDh0Dw It´s not so important, it´s just making the "getContext" function. Whats important, in teh commandline "student.firstName = StudentsStruct.firstName" i´m getting the error "instance member "firstName" cannot be used on type ViewController.StudentStruct. After trying and trying, i´m running out of ideas how to get the array of structs into coredata.

这是DatabaseController文件:

This is the DatabaseController file:

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.这是我当前的代码:

Ok, you are right, i forgot to execute the fetchrequest. Here´s my current code:

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; firstName = nil; lastName = nil;

It´s running without errors. Now i´m getting 32 search results. Every entry is: age = 0; firstName = nil; lastName = nil;

为进行比较,此代码在没有循环的情况下有效:

For comparison, this code, without the loop is working:

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

    }

}

推荐答案

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

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

        }

    }

}

就这样.

这篇关于结构数组:如何保存在coredata中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆