我正在使用2个托管对象上下文来有效地重视后台的大型数据集。我确保我在线程中一次只使用1个托管对象上下文。
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
MetricType *metricType = [self metricTypeForName:self.metricName fromContext:context];
NSLog(@"metric context %@", [metricType managedObjectContext]);
[self processDataInContext:context forMetric:metricType];
在上面的剪辑代码中,NSLog正确地打印出我正在使用的managedObjectContext的地址。然后我继续使用processDataInContext - 这只是一个私有方法来交互json数据数组并添加对象。每个对象都与MetricType有关系。
然而,当我去关联他们时
metric.metricType = metricType;
我收到错误:非法尝试在不同上下文中的对象之间建立关系'metricType'....即使我确保我不这样做。
当我在此行之前进行日志输出时:
NSLog(@"My Context %@", context);
NSLog(@"metric context %@", [metricType managedObjectContext]);
metricType上下文返回nil !!
它如何变得稀饭?我并没有这样做,这似乎是它抱怨的原因。
答案 0 :(得分:0)
我想通了
[context reset];
..每50条记录被调用一次,这当然是从上下文中删除我的metricType对象而我没有重新获取它。
答案 1 :(得分:0)
初始化metricType的方式看起来很可疑。 [self metricType:fromContext:]实际上做了什么来返回MetricType实例?您是否使用[[MetricType alloc] init]创建新的MetricType?我怀疑你在自动发布池中返回了一些东西