作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好的,让我们从代码开始。我正在遍历返回的字典数组并基于它们创建(或更新)对象。在这种方法中,我正在尝试查找或创建一个新实体。然后,如果该对象应该被删除,我想这样做,而不是浪费时间用新信息更新它。
- (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];
}
NSUnderlyingException=Cannot update object that was never inserted.
*** 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>''
最佳答案
更容易获得 RKManagedObjectStore
[[RKObjectManager sharedManager] objectStore]
的实例(假设您想要共享的,因为您正在调用您的应用程序委托(delegate),所以您似乎这样做了)。
检查 deleted_at
创建 NSManagedObject 之前的 key 。此代码假定您要转换为类型 Resource
,它是 NSManagedObject
的子类.它未经测试,但应该让你知道你应该做什么。
- (void)updateOrCreateObjectWith:(NSDictionary*)dictionary {
RKManagedObjectStore *objectStore = [[RKObjectManager sharedManager] objectStore];
//get a reference to the object
Resource *resource = [Resource findFirstByAttribute:@"myID" withValue:[dictionary objectForKey:@"id"]];
//see if "deleted_at" exists in dictionary
if ([[dictionary objectForKey:@"deleted_at"] isKindOfClass:[NSString class]])
{
//check to see if object exists in the context
if(resource)
{
//if it exists, delete it
[objectStore.managedObjectContext deleteObject:resource];
}
} else {
//no "deleted at", so create the object
if (!resource) {
//resource is nil (it doesn't exist in the context), so we need to create it
resource = [Resource object];
}
[resource updateWith:dictionary];
}
NSError *error = nil;
[objectStore.managedObjectContext save:&error];
if (error) {
NSLog(@"error saving before delete: %@",error);
}
}
关于objective-c - 如何从 NSManagedObjectContext 中删除新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9987220/
我是一名优秀的程序员,十分优秀!