我想我理解错误消息:CoreData无法履行错误,但我不知道该如何处理它。当HTTP服务更新对象时,CoreData无法完成故障
我们有一个应用程序,我们使用Core Data来保存从JSON服务返回的数据。今天我正在做以下事情。
- 从持久性存储中获取本地对象,并返回到UI
- 询问服务器如果对象被更新 - 当我得到的答案,我更新了核心数据管理对象
- 更新UI与更新的对象
问题是;即使我不使用多线程,当HTTP请求删除我的UI保留的托管对象时,我有时也会收到错误。我试图用returnsObjectsAsFaults将对象提取为NO。我想我可以访问所有的管理对象的关系和属性,即使它被删除了(只要我的用户界面保留了它)。
我应该如何解决这个问题?
我想我可以使用单独的NSManagedObjectContext进行读取和写入。我做了这个测试:
MyAuthorMO *authorUpdate = [[MyAuthorMO alloc] init]; // I have made this init insert the object into the updateContext
authorUpdate.firstname = @"Hans";
authorUpdate.lastname = @"Wittenberg";
authorUpdate.email = @"[email protected]";
NSManagedObjectContext *updateContext = [[MyCoreManager getInstance] managedObjectContext];
NSError *error = nil;
[updateContext save:&error];
NSManagedObjectContext *readContext = [[MyCoreManager getInstance] readOnlyContext];
NSFetchRequest *fetchRequest = [managedObjectModel fetchRequestFromTemplateWithName:@"authorByEmail" substitutionVariables:[NSDictionary dictionaryWithObject:@"[email protected]" forKey:@"EMAIL"]];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSArray *authors = [readContext executeFetchRequest:fetchRequest error:&error];
MyAuthorMO * readAuthor = [authors objectAtIndex:0];
// Delete the author with update context:
[updateContext deleteObject:authorUpdate];
[updateContext save:&error];
NSLog(@"Author: %@ %@, (%@)", readAuthor.firstname, readAuthor.lastname, readAuthor.email);
只要我使用readContext进行读取,日志输出就好了。如果我使用updateContext进行提取,我会得到一个异常。这看起来很有前途,但恐怕我会在后期遇到问题。迟早我可能会尝试访问一个不完全提取的属性(一个错误)。我如何实现我正在寻找的行为?
尼克,你可能是对的。我已阅读我以前的帖子并接受了最佳解决方案。谢谢你的评论。 – Andi 2010-09-10 06:11:52