在NSSet中查找NSManagedObject的最快方法

时间:2013-06-16 10:07:50

标签: cocoa-touch core-data nsset

我有2个NSSets和NSManagedObjects,每个集合的对象都在不同的线程中获取,这意味着一些对象具有匹配的objectID,但对象本身是不同的。现在我想从一个集合中删除托管对象。

NSSet* oldObjects;
NSMutableSet* currentObjects;

// I want to remove the managedObjects in oldObjects from currentObjects, all objects in oldObjects are also in currentObjects

// This doesn't work, since the objects don't match
[currentObjects removeObjectsInArray:[oldObjects allObjects]]; 

// But strangely enough, this doesn't add any objects to currentObjects, but if the objects don't match, shouldn't it?
//[currentObjects addObjectsFromArray:[oldObjects allObjects]];


// This does work for me but this code is running on the main thread and I can see this becoming rather slow for large data sets
NSArray* oldObjectIDs = [[oldObjects allObjects] valueForKey:@"objectID"];
[currentObjects filterUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (objectID IN %@)", oldObjectIDs]];

我可以更快地过滤掉这些吗?即使在这种情况下,快速枚举会更快吗?

1 个答案:

答案 0 :(得分:0)

很抱歉有这样的延迟。

我重新阅读了你的问题,现在,我完全理解了设置,我可能会为你找到解决方案。

这未经过测试,但请尝试以下方法:

//Since the current objects set has registered its objects in the current context
//lets use that registration to see which of them is contained in the old object set
NSMutableSet* oldRegisteredSet = [NSMutableSet new];
for (NSManagedObject* o in oldObjects) {
    NSManagedObject* regObject = [context objectRegisteredForID:[o objectID]];
    if (regObject) {
        //You could do here instead: [currentObjects removeObject:regObject];
        //You should optimize here after testing performance
        [oldRegisteredSet addObject:regObject];
    }
}

[currentObjects minusSet:oldRegisteredSet];