【发布时间】:2012-04-03 04:41:08
【问题描述】:
好的,让我们从代码开始。我正在遍历返回的字典数组并基于它们创建(或更新)对象。在这种方法中,我正在尝试查找或创建一个新实体。然后如果该对象应该被删除,我想这样做,而不是浪费时间用新信息更新它。
- (void)updateOrCreateObjectWith:(NSDictionary*)dictionary {
RKManagedObjectStore *objectStore = ((MyAppDelegate*)[[UIApplication sharedApplication] delegate]).objectStore;
id updateObject = (NSManagedObject*)[objectStore findOrCreateInstanceOfEntity:[resource entity] withPrimaryKeyAttribute:@"myID" andValue:[dictionary objectForKey:@"id"]];
[updateObject setMyID:[dictionary objectForKey:@"id"]];
// if marked for deletion, delete it now
if ([[dictionary objectForKey:@"deleted_at"] isKindOfClass:[NSString class]]) {
if ([updateObject isNew]){
NSError *error = nil;
[objectStore.managedObjectContext save:&error];
if (error) {
NSLog(@"error saving before delete: %@",error);
return;
}
// [objectStore.managedObjectContext deleteObject:updateObject];
// [objectStore.managedObjectCache delete:updateObject];
}
else {
[objectStore.managedObjectContext deleteObject:updateObject];
}
return;
}
[updateObject updateWith:dictionary];
}
需要注意的部分是 deleted_at 部分,其中包含 (1) 保存部分,(2) 从上下文中删除对象,以及 (3) 从缓存中删除对象。我已经尝试了这三者的几种组合,但都没有得到想要的结果。
如果我从缓存中删除它(仅 #3):
- 对象已保存,但它们没有属性。
如果我从托管上下文中删除它(仅 #2),我会得到:
NSUnderlyingException=Cannot update object that was never inserted.
由于它从未插入,我想我会保存它然后删除它(#1和#2),但后来我得到:
*** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0xed27810 <x-coredata://4EE6AD5A-CC34-460A-A97A-0909454126A4/User/p166>''
那么从 NSMangedObjectContext 中删除“新”对象的正确方法是什么?
【问题讨论】:
标签: objective-c nsmanagedobject restkit nsmanagedobjectcontext