问题描述
在这里想象一下Tinder应用程序,该应用程序将收到世界各地的用户个人资料列表。现在,如果应用程序用户将任何个人资料标记为收藏,那么我想将其保存在核心数据中。
我实现的方法是,确认对NSManagedobject类的可解码协议,以便我可以轻松地分析用户的响应并创建核心数据对象。
问题是,当我保存上下文时,将保存所有配置文件,而我只希望保存最喜欢的配置文件。
这是我的班级样子的代码段。
// MARK: - Name
class Name:NSManagedobject,Codable {
@NSManaged var title: String
@NSManaged var first: String
@NSManaged var last: String
enum CodingKeys: String,CodingKey {
case title = "title"
case first = "first"
case last = "last"
}
init() {
super.init(entity: NSEntityDescription.entity(forEntityName: String.init(describing: Name.self),in: PersistenceController.shared.context)!,insertInto: PersistenceController.shared.context)
}
@objc
private override init(entity: NSEntityDescription,insertInto context: NSManagedobjectContext?) {
super.init(entity: entity,insertInto: context)
}
convenience init(title: String,first: String,last: String) {
self.init()
self.title = title
self.first = first
self.last = last
}
// MARK: - Decodable
required convenience init(from decoder: Decoder) throws {
self.init()
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decodeIfPresent(String.self,forKey: .title) ?? ""
first = try values.decodeIfPresent(String.self,forKey: .first) ?? ""
last = try values.decodeIfPresent(String.self,forKey: .last) ?? ""
}
// MARK: - encodable
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(title,forKey: .title)
try container.encode(first,forKey: .first)
try container.encode(last,forKey: .last)
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)