2017-04-13 83 views
2

嗨,我是用CoreData项目,并从服务器JSON响应工作更新实体。我的目标是创建一个Entityfailableinitializerjson参数,它首先会检查entity已经存在(通过检查属性“ID”比较JSON [“ID]字段,如果实体已经存在。在initializer将只与json更新实体。如果实体不存在,则initializer将创建一个新的实体和更新的新实体的属性与json斯威夫特CoreData创建或JSON

任何人都知道如何才能创建failable初始化

我都试过,但不知道它是正确与否(有一些展开可选的帮助非常感谢,谢谢!

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 
    } 

} 
+0

任何人有理想是什么? –

+0

您是否收到编译器错误?什么线?它以前如何? –

+0

喜不存在编译器错误,但我不知道它的正确与否。还有一两件事没有对检查对象存在之前创建新的实体 –

回答

1

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

我会做的是添加一个类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) 
} 
+0

感谢您的答复。所以我们如何结合这一点。上述初始化程序仍然正确。我们只需要添加一个类func findOrCreate? –

+0

这就是我的建议。另外,如果json没有你需要的键,你可以通过返回nil来改进你的init。 –

+0

您好可以帮助findOrCreate的内容。似乎会有一些重复的内部比较初始化 –