Jor*_*oto 3 core-data nsmanagedobject ios swift
我有一个NSManagedObject子类,需要在正确返回之前完成它(它的所有字段都是非选项),所以当我执行init时,首先我使用一个guard来确保数据(来自JSON)是正确的如下:
public init(context: NSManagedObjectContext, dictionary: [String: AnyObject]) throws {
guard
let modified_on = date(dictionary["modified_on"] as? String),
let start_on = date(dictionary["start_on"] as? String),
let end_on = date(dictionary["end_on"] as? String),
let ticket_name = dictionary["ticket_name"] as? String
else {
throw ErrorParseModel.ErrorParsing
}
...
...
Run Code Online (Sandbox Code Playgroud)
问题是编译器返回一个错误,Super.init isn't called before returning from initializer因为这个init方法可能抛出异常而不调用super.init之前.
我的家伙是关于如何进行的:1.我之前是否应该打电话给super.init并创建一个"虚拟对象"而不是后卫?在这种情况下,我应该从上下文中删除此对象之前抛出异常?2.在此警卫之前我可以做的另一个测试是确保entityName正确如下:
guard let entity = NSEntityDescription.entityForName(Ticket.entityName, inManagedObjectContext: context) else {
return
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我无法在上下文中创建对象,因为我没有实体,所以我不可能(我认为)在一个上下文中创建一个nil-entity对象.
有关如何进行的任何建议?
谢谢!
可以通过实现便利初始化程序而不是专用初始化程序来解决"从初始化程序返回之前未调用Super.init"问题:
public convenience init(context: NSManagedObjectContext, dictionary: [String: AnyObject]) throws {
guard let entity = NSEntityDescription.entityForName(Ticket.entityName, inManagedObjectContext: context) else {
throw ErrorParseModel.EntityNotFound
}
guard
let modified_on = date(dictionary["modified_on"] as? String)
// ...
else {
throw ErrorParseModel.ErrorParsing
}
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.modified_on = modified_on
}
Run Code Online (Sandbox Code Playgroud)
但是,在我看来,如果找不到核心数据实体,则抛出错误没有多大意义.这将是一个编程错误,并且没有合理的方法来捕获并在运行时解决该问题.我会将其视为致命错误,以便在测试应用程序时及早检测到它:
guard let entity = NSEntityDescription.entityForName(Ticket.entityName, inManagedObjectContext: context) else {
fatalError("Entity not found")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
495 次 |
| 最近记录: |