繁体   English   中英

Swift CoreData 从 JSON 创建或更新实体

[英]Swift CoreData create or update entity from JSON

嗨,我正在处理CoreData项目和来自服务器的JSON响应。 我的目标是从json参数创建一个Entity failable initializer ,它首先检查entity已经存在(通过检查属性“id”与 json[“id] 字段进行比较。如果实体已经存在。 initializer将只用json更新实体。如果实体不存在, initializer将创建一个新实体并使用json更新新实体的属性。

如何创建可失败的初始化程序?

我试过这个,但不知道它是否正确(有一些解包可选。

import SwiftyJSON
import CoreData

extension Movie {
    struct Keys {
        static let id = "id"
        static let title = "title"
    }

    convenience init?(in context: NSManagedObjectContext!, with json: JSON?) {

        self.init(entity: NSEntityDescription.entity(forEntityName: "Movie", in: context)!, insertInto: context)
        guard let json = json else {
            return nil
        }
        id = json[Keys.id].numberValue
        title = json[Keys.title].string

    }

    func update(from json: JSON?) {
        guard let json = json else {
            return
        }

        id = json[Keys.id].numberValue
        title = json[Keys.title].string
    }

}

我不认为 init 是查找现有对象的正确位置。

我要做的是向 Movie 添加一个类 func 来查找或创建一个 Movie 对象,例如:

/// Returns an existing Movie if the id exists, or a new one if not.
/// Can return nil if json is nil or missing keys
class func findOrCreate(in context: NSManagedObjectContext!, with json: JSON?) -> Movie? {
    // If JSON is nil, return nil
    //  (your code here)
    // Look for an existing movie and return it if you find one
    //  (your code here)

    // If there is no existing one call the init
    return Movie(in: content, with: json)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM