当尝试在第二个 NSManagedObjectContext 中添加核心数据对象时,我收到一条错误消息,指出非法尝试在不同上下文中的对象之间建立关系“信息”。但是,这两个实体位于相同的上下文中(至少,它们应该)。调试器给出相同的十六进制数。这段代码有什么问题?
-(void) loadHistoricalPrices
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Create context on background thread
if(document!=NULL)
{
NSManagedObjectContext *context = NULL;
NSNotificationCenter *nc =NULL;
context = [[NSManagedObjectContext alloc] init];
[context setUndoManager:nil];
[context setPersistentStoreCoordinator: [document.managedObjectContext persistentStoreCoordinator]];
// Register context with the notification center
nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:context];
NSEntityDescription * infoEntity;
infoEntity = [NSEntityDescription entityForName:@"Info" inManagedObjectContext:context];
NSEntityDescription * historyEntity;
historyEntity = [NSEntityDescription entityForName:@"History" inManagedObjectContext:context];
// fetching an object-array of info-entity, called result
if([result count]>0)
{
NSArray * items;
// getting items to insert into history-entity
for(NSString * item in items)
{
NSArray * subs;
subs=[item componentsSeparatedByString:@","];
if([subs count]>5)
{
HistoryMO * newHistory;
newHistory = [[[HistoryMO alloc] initWithEntity:historyEntity insertIntoManagedObjectContext:context] autorelease];
[newHistory setValue:[NSNumber numberWithDouble:[[subs objectAtIndex:4] doubleValue]] forKey:@"course"];
[newHistory setValue:infoMO forKey:@"info"];
// >>>>> CRASHES HERE
}
}
}
// merge data
if([[[context persistentStoreCoordinator] persistentStores] count]>0)
{
NSLog(@"saving...");
error=NULL;
[context save:&error];
if (!error) [context reset]; else NSLog(@"error saving historic prices %@",[error localizedDescription]);
if (!error) NSLog(@"saved successfully");
}
[nc removeObserver:self];
[context release];
}
[pool release];
}