【问题标题】:Swift CoreData create or update entity from JSONSwift CoreData 从 JSON 创建或更新实体
【发布时间】:2017-04-13 13:05:52
【问题描述】:

您好,我正在处理 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
    }

}

【问题讨论】:

  • 您是否遇到编译器错误?什么线?那是什么?
  • 您好,没有编译器错误,但我不知道它是否正确。还有一件事是在创建新实体之前没有检查存在的对象

标签: ios swift core-data initialization


【解决方案1】:

我不认为 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)
}

【讨论】:

  • 感谢您的回复。那么我们如何结合这个。上面的初始化程序仍然是正确的。我们只需要添加一个类 func findOrCreate?
  • 这就是我的建议。此外,如果 json 没有您需要的密钥,您可以通过返回 nil 来改进您的初始化。
  • 您好,可以帮忙看看 findOrCreate 的内容。与初始化程序相比,似乎内部会有一些重复
  • 重复的代码总是可以放到其他函数中。先让它工作,然后尝试将常用代码重构为函数。
  • 谢谢。设法使它工作。 1 最后一个问题,如果来到现有电影并需要更新。如果有变化,我们如何才能更新?将每个值与 json 或任何其他方式进行比较?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2011-11-14
  • 2011-01-21
相关资源
最近更新 更多