Cha*_*ang 5 json core-data ios swift decodable
我正在使用 CoreData 和 JSON 解析与 Decodable 进行后续操作,并在初始化程序末尾遇到错误'self.init' isn't called on all paths before returning from initializer:
import Foundation
import CoreData
extension CodingUserInfoKey {
static let managedObjectContext = CodingUserInfoKey(rawValue: "managedObjectContext")!
}
@objc(Task)
public class Task: NSManagedObject, Decodable {
enum CodingKeys: String, CodingKey {
case diff, title, desc, doc
}
required convenience public init(from decoder: Decoder) throws {
guard let context = decoder.userInfo[CodingUserInfoKey.managedObjectContext] as? NSManagedObjectContext else {
print("Decode context error")
return
}
guard let entity = NSEntityDescription.entity(forEntityName: "Task", in: context) else {
print("Decode entity error")
return
}
self.init(entity: entity, insertInto: context)
do {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.diff = try container.decode(String.self, forKey: .diff)
self.title = try container.decode(String.self, forKey: .title)
self.desc = try container.decode(String.self, forKey: .desc)
self.doc = try container.decode(String.self, forKey: .doc)
} catch {
print("Decode key error")
}
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
您可能应该在语句中抛出自定义错误,guard而不是仅仅返回。您还应该do-catch从解码器函数调用中删除:
enum ManagedObjectError: Error {
case decodeContextError
case decodeEntityError
}
required convenience public init(from decoder: Decoder) throws {
guard let context = decoder.userInfo[CodingUserInfoKey.managedObjectContext] as? NSManagedObjectContext else {
throw ManagedObjectError.decodeContextError
}
guard let entity = NSEntityDescription.entity(forEntityName: "Task", in: context) else {
throw ManagedObjectError.decodeEntityError
}
self.init(entity: entity, insertInto: context)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.diff = try container.decode(String.self, forKey: .diff)
self.title = try container.decode(String.self, forKey: .title)
self.desc = try container.decode(String.self, forKey: .desc)
self.doc = try container.decode(String.self, forKey: .doc)
}
Run Code Online (Sandbox Code Playgroud)