使用CoreData,如何确定NSManagedObject是否在特定上下文中?

时间:2014-10-26 06:35:02

标签: ios core-data nsmanagedobject nsmanagedobjectcontext

在核心数据中,您只能通过从中获取对象的上下文来操作对象。这意味着,如果你有两个上下文,我们称之为mainContext和backGround上下文,backGround上下文必须只更新backgroundContext中的对象,而mainContext只能更新mainContext中的对象。这听起来很简单。

这是我的问题。我有一个来自未知上下文的对象,我如何确定该对象是来自mainContext还是backgroundContext?我知道managedObject有一个指向其managedObjectContext的指针,名为“managedObjectContext”,但我不知道如何将它与我的指向mainContext和backgroundContext的指针进行比较,以便查看它所在的指针?请帮忙。

2 个答案:

答案 0 :(得分:0)

你所拥有的地方:

id yourMainContext = ...
id yourBGContext = ...

现在检查上下文:

id yourObjectsContext = yourObject.managedObjectContext;
BOOL equalToMain = [yourObjectsContext isEqual:yourMainContext];
BOOL equalToBG = [yourObjectsContext isEqual:yourBGContext];

完整解决方案

存储mainQueue / BGQueue的上下文,您也可以使用函数dispatch_queue_set_specific

你所拥有的地方:

id yourMainContext = ...
dispatch_queue_set_specific(dispatch_get_main_queue(), "MOC", yourMainContext);

和其他地方

id yourBGContext = ...
dispatch_queue_set_specific(theBGQueue, "MOC", yourBGContext);

现在稍后检查上下文:

id queueContext = dispatch_get_specific("MOC");
assert(queueContext);

id yourObjectsContext = yourObject.managedObjectContext;
BOOL equalToQueue = [yourObjectsContext isEqual:queueContext];
//SAFE TO MODIFY    

答案 1 :(得分:0)

现在在IOS8中,NSManagedObjectContext有一个属性名称,你可以使用它并比较:

[yourObjectsContext.name isEqualToString:yourBGContext.name]