gpt4 book ai didi

ios - 从初始化程序返回之前,并非在所有路径上都调用'self.init'

转载 作者:行者123 更新时间:2023-12-01 15:54:31 24 4
gpt4 key购买 nike

我正在this之后使用Decodable进行CoreData和JSON解析,并且在初始化器的末尾遇到错误'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")
}
}

}

我想念什么吗?

最佳答案

您可能应该在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)
}

关于ios - 从初始化程序返回之前,并非在所有路径上都调用'self.init',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63636431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com