[英]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.