我正在使用 Codable 创建 NSManagedObjects,jsondecode.decode([User].self, from: jsonDataRaw)
但我的问题是 decode.decode() 每次都会创建一个新对象,但我需要一种方法来使用 jsonData 更新现有对象,而不是创建新对象。
有没有办法使用 Codable 做到这一点?
class User : NSManagedObject, Codable {
required convenience init(from decoder: Decoder) throws {
guard let contextUserInfoKey = CodingUserInfoKey.context,
let managedObjectContext = decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: MERUser.entityName, in: managedObjectContext) else {
fatalError("Failed to decode")
}
self.init(entity: entity, insertInto: managedObjectContext)
try update(with: decoder)
}
func update(with decoder: Decoder) throws {
// Decode
guard let values = try? decoder.container(keyedBy: CodingKeys.self) else {
assertionFailure("no decoder")
return …Run Code Online (Sandbox Code Playgroud) 我使用NSLock得到此错误,我试图通过使用unlockWithCondition(使用NSConditionLock)来规避,但无论我得到相同的结果:
*打破_NSLockError()进行调试.* - [NSLock unlock]:lock('(null)')从没有锁定它的线程解锁.
我不确定它是不是很糟糕,但我在做的是这样的:
new Thread:
[lockA lock];//waiting unlock
[lockB lock];//waiting unlock
..shared code..
[lockA unlock];
[lockB unlock];
in Main Thread:
//Do two HTTP request.
//when request respond, I unlock the locks in respective threads with [lockA unlock];
[lockB unlock];
Run Code Online (Sandbox Code Playgroud)
所以"..shared code .."部分可以执行.我不明白为什么我得到这个错误.
谁能解释我做错了什么?它看起来应该完美无缺.