很简单的情况。不知道为什么会导致问题。
我有一个在子 NSManagedObjectContext 中创建新 NSManagedObject 的视图。当用户按下“完成”时,它会保存子上下文,然后保存父上下文,然后使用新创建的对象的 objectID 发布通知。在主视图控制器中,我响应通知并尝试使用existingObjectWithID:error:
.
问题是这失败了,因为 objectID 是临时的(我收到“Cocoa 错误 133000”)。这两个上下文的保存是完美的:当我重新加载应用程序时,我可以看到我创建的条目。但是当我需要获取对新对象的引用时,它失败了。
为什么在我保存后它会给我一个临时对象 ID?
注意:我已经尝试使用obtainPermanentIDsForObjects:error:
,它可以工作,但是当我尝试使用它来获取对象时,永久 ID 仍然失败。
这是一些代码:
-(IBAction)done:(id)sender
{
if ([editorDoneNotification isEqualToString:kNOTIFICATION_OBJECTADDED]) {
// save the temporary moc
NSError* e;
if (![self.tempContext save:&e]) { // this is always a successful save
NSLog(@"Failed to save temporary managed object context: %@", [e localizedDescription]);
[[[UIAlertView alloc] initWithTitle:@"Database Error"
message:@"Failed to add object."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}
NSError* e;
if (![[[AMDataModel sharedDataModel] mainContext] save:&e]) { // this is also successful
NSLog(@"Failed to save main managed object context: %@", [e localizedDescription]);
[[[UIAlertView alloc] initWithTitle:@"Database Error"
message:@"Failed to edit object."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
else
[[NSNotificationCenter defaultCenter] postNotificationName:editorDoneNotification object:[self.editingObject objectID]];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
这就是我回复通知的方式:
-(void)objectAdded:(NSNotification*)notification
{
if (self.popoverController && [self.popoverController isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
}
NSManagedObjectID* newObjectID = (NSManagedObjectID*)(notification.object);
NSError* error;
AMObject* object = (AMObject*)[[[AMDataModel sharedDataModel] mainContext] existingObjectWithID:newObjectID error:&error]; // this is where the cocoa error 133000 happens
if (error != nil) {
NSLog(@"ERROR: Could not load new object in main managed object context.");
}
GMSMarker* m = [[GMSMarker alloc] init];
m.position = CLLocationCoordinate2DMake(object.latitudeValue, object.longitudeValue);
m.userData = object;
m.map = self.mapView;
[self.markers addObject:m];
}
-(void)objectEdited:(NSNotification *)notification
{
NSManagedObjectID* editedObjectID = (NSManagedObjectID*)notification.object;
NSError* error = nil;
AMObject* object = (AMObject*)[[[AMDataModel sharedDataModel] mainContext] existingObjectWithID:editedObjectID error:&error];
if (error != nil) {
NSLog(@"Error could not load edited object in main managed object context");
}
//update the UI based on edit
if ([self.popoverController isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
self.popoverController = nil;
}
}