How to Store and Fetch Json Model data to Coredata in Swift

久未见 提交于 2019-12-07 07:59:27

My suggestion is to use one entity.

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

    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!