如何在Swift中将Json Model数据存储和提取到Coredata [英] How to Store and Fetch Json Model data to Coredata in Swift

查看:200
本文介绍了如何在Swift中将Json Model数据存储和提取到Coredata的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我早就使用过coredata。但是,我知道用于存储数据和获取数据的coredata的基础知识。

I have used coredata long back. But, I know basics of coredata for storing data and fetching.

但是,目前我正在使用Swift语言。

But, Presently I am working with Swift language.

我有本地json文件,我正在通过解码器进行解析,并在表格视图中显示该数据。

I have local json file and I am doing parsing that by decoder and displaying that data in tableview.

let path = Bundle.main.path(forResource: "file", ofType: "json")

do {
    let data = try Data(contentsOf: URL(fileURLWithPath: path ?? ""), options: .mappedIfSafe)
    let decoder = JSONDecoder()
    do {
        quData = try decoder.decode(quData.self, from: data)
        DispatchQueue.main.async {
            self.myTableView.reloadData()
        }
    } catch {
        print("Json decoder error")
    }
} catch {
    print(LocalizedError.self)
}

为此,我创建了基于

但是,现在我必须将该数据存储到Coredata并取回,需要显示在同一张表视图中。

But, Now I have to store that data to Coredata and Fetch back, Need to show in same tableview.

但是,我感到困惑的是,我需要创建多少个键值。

But, I am getting confusion how many key values should I need to create.

我的模型类是:

class QuData: Codable {
    let qu: Qu

    init(qu: Qu) {
        self.qu = qu
    }
}

class Qu: Codable {
    let music: Music
    let dance: dance

    init(music: Music, dance: dance) {
        self.music = music
        self.dance = dance
    }
}

class Maths: Codable {
    let q1, q2: Q1

    init(q1: Q1, q2: Q1) {
        self.q1 = q1
        self.q2 = q2
    }
}

class Q1: Codable {
    let query: String
    let options: [String]
    let answer: String
    let q1Optional: Bool

    enum CodingKeys: String, CodingKey {
        case query, options, answer
        case q1Optional = "optional"
    }

    init(question: String, options: [String], answer: String, q1Optional: Bool) {
        self.query = query
        self.options = options
        self.answer = answer
        self.q1Optional = q1Optional
    }
}

class Sport: Codable {
    let q1: Q1

    init(q1: Q1) {
        self.q1 = q1
    }
}

还有我的JSON数据是

And my JSON data is

{
    "qu": {
        "music": {
            "q1": {
                "query": "What is your name?",
                "options": [
                    "Sony",
                    "Samsung",
                    "Apple",
                    "MI"
                ],
                "answer": "Apple",
                "optional": true

            }
        },
        "dance": {
            "q1": {
                "question": "5 + 1 = ?",
                "options": [
                    "8",
                    "9",
                    "6",
                    "23"
                ],
                "answer": "23",
                "optional": false
            },
            "q2": {
                "question": "12 - 4 = ?",
                "options": [
                    "5",
                    "4",
                    "9",
                    "6"
                ],
                "answer": "4",
                "optional": false
            }
        }
    }
}

如何将这些数据存储到Coredata并进行提取,在表格视图中显示。

How to store these data to Coredata and fetching, Showing in tableview..

并且,在json数据中的两个类别(音乐,舞蹈),我必须显示第一部分的音乐数据和
部分的tableview中的舞蹈数据。

And, The two categories (music,dance) in json data, I have to show "Music" data in 1st section and "Dance" data in section tableview.

我很震惊,如何在Entity中使用属性创建这种json结构并使用相同的方式获取它们模型类(已经为本地json文件解析创建了模型类。)。

I am fully struck, how to create this kind json structure in Entity with attributes and fetching them using same model class (Which already created for local json file parsing).

有人可以建议我继续吗?

Can anyone suggest me to move on further?

推荐答案

我的建议是使用一个实体。

My suggestion is to use one entity.

在Core Data中,您可以非常有效地过滤记录,因此添加一个表示 type 属性音乐舞蹈等。您甚至可以添加计算属性来映射 type 属性枚举选项属性声明为平面字符串。使用另一个计算属性将平面字符串映射到数组,反之亦然。

In Core Data you can filter records very efficiently, so add a type attribute representing music, dance etc. You can even add a computed property to map the type attribute to an enum. The options attribute is declared as flat string. Use another computed property to map the flat string to an array and vice versa.

class Question : NSManagedObject {

    @NSManaged var type: String
    @NSManaged var question: String
    @NSManaged var answer: String
    @NSManaged var options: String
    @NSManaged var optional: Bool

    enum QuestionType : String {
        case music, dance
    }

    var questionType : QuestionType {
        get { return QuestionType(rawValue: type)! }
        set { type = newValue.rawValue }
    }

    var questionOptions : [String] {
        get { return options.components(separatedBy: ", ") }
        set { options = newValue.joined(separator: ", ") }
    }






或者对于每种类型和关系使用一个实体


Alternatively use one entity per type and relationships for the questions

class Music : NSManagedObject {

    @NSManaged var questions: Set<Question>

    ...
}


class Question : NSManagedObject {

    @NSManaged var question: String
    @NSManaged var answer: String
    @NSManaged var options: String
    @NSManaged var optional: Bool

    @NSManaged var type: Music

    ...
}

这篇关于如何在Swift中将Json Model数据存储和提取到Coredata的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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