核心数据:我的托管对象上的托管对象上下文为零
我使用 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!
怎么变成零了?我没有将其归零,这似乎是它抱怨的原因。
I'm using 2 managed object contexts for efficiently important a large data set in the background. I'm ensuring I'm only using 1 managed object context at a time in the thread.
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];
In the snipped of code above, the NSLog correctly prints out the address of the managedObjectContext i'm using. I then go on to processDataInContext - which is just a private method to interate over a json data array and add objects. Each object has a relationship to the MetricType.
However, when I go to associate them
metric.metricType = metricType;
I get the error: Illegal attempt to establish a relationship 'metricType' between objects in different contexts.... even though I'm ensuring I don't do this.
When I do a log output before this line:
NSLog(@"My Context %@", context);
NSLog(@"metric context %@", [metricType managedObjectContext]);
The metricType context returns nil!!
How has it become nilled? I didn't nil it and this seems to be the reason its complaining.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现
......每 50 条记录就被调用一次,这当然是从上下文中删除我的 metricType 对象,并且我没有重新获取它。
I figured it out
..was being called every 50 records, which of course was removing my metricType object from the context and I wasn't re-fetching it.
初始化 metricType 的方式看起来很可疑。 [self metricTypeForName:fromContext:] 实际上是做什么来返回 MetricType 实例的?您是否正在使用 [[MetricType alloc]init] 创建新的 MetricType?我怀疑您正在返回自动释放池中的某些内容
The way you initialize metricType looks fishy. What does [self metricTypeForName:fromContext:] actually do to return a MetricType instance? Are you creating a new MetricType using [[MetricType alloc]init]? I suspect you are returning something in an auto-release pool