此init
函数每次都插入一个新实体,即使user_id
相同。
我该如何解决?我希望每个实体仅与user_id成为一个。
我的代码是这样的:
public convenience init(from decoder: Decoder) throws {
// Create NSEntityDescription with NSManagedObjectContext
guard let contextUserInfoKey = CodingUserInfoKey.managedContext,
let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext) else {
fatalError("Failed to decode User!")
}
self.init(entity: entity, insertInto: managedObjectContext)
let userInfo = try decoder.container(keyedBy: UserInfoKeys.self)
username = try userInfo.decodeIfPresent(String.self, forKey: .username)
user_id = try userInfo.decode(String.self, forKey: .user_id)
}