1
我在coredata NSManagedObjectContextDidSaveNotification運行的謂詞來過濾相關的對象我感興趣的。predicateWithFormat很慢
- (void)didSaveNotficiation:(NSNotification*)notification
{
NSSet *objects = nil;
NSMutableSet *combinedSet = nil;
NSPredicate *predicate = nil;
NSDictionary *userInfo = [notification userInfo];
objects = [userInfo objectForKey:NSInsertedObjectsKey];
combinedSet = [NSMutableSet setWithSet:objects];
objects = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
[combinedSet unionSet:objects];
objects = [[notification userInfo] objectForKey:NSDeletedObjectsKey];
[combinedSet unionSet:objects];
//THis is slow
predicate = [NSPredicate predicateWithFormat:@"entity.name == %@ && %K == %@",
[XXContact entityName], XXContactRelationship.user,self];
[combinedSet filterUsingPredicate:predicate];
if ([combinedSet count] == 0) {
return;
}
[self process];
/* This is much faster
[combinedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
if ([obj isKindOfClass:[XXContact class]]) {
XXContact* contact = (XXContact*)obj;
if (contact.user == self) {
[self process];
*stop = YES;
}
}
}];
*/
}
的通知可以被調用時超過100倍,應用程序啓動。 當我剖析應用程序時,似乎函數predicateWithFormat太慢了,佔用了CPU的20%。它甚至不是過濾緩慢。謂詞本身的創建非常緩慢。 如果將其更改爲使用enumerateObjectsUsingBlock,它變得更快,但代碼的可讀性較差。
有沒有人有解釋?謝謝。