ios - Swift CoreData 从 JSON 创建或更新实体

标签 ios swift core-data initialization

您好,我正在使用 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)
}

关于ios - Swift CoreData 从 JSON 创建或更新实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43393171/

相关文章:

ios - NSFileWrapper 在来自 iCloud 时失败并在本地目录中工作

ios - 向 NSNotificationCenter 添加/删除观察者的最佳实践

ios - Firebase - 如何检索日期范围内的对象?

javascript - 如何从 wkwebview 调用 javascript 函数?

ios - Cocoapods安装

objective-c - 用于按组选择具有最大值的行的 NSPredicate

ios - 向核心数据对象或属性添加弃用

ios - 防止节点离开边界

android - FlatList Sticky header 在 ScrollView 中不起作用?

ios - iOS中如何管理数据库