我有一个SearchStringTooltip ManagedObject。具有属性@dynamic tooltipText;(NSString)

我需要在数据库中动态添加新的工具提示,但是我只需要唯一值(不敏感)。

它们一次可以超过100个。并且每次我检查唯一性..

看起来像:

    if (newTooltips.count == 0)
        return;

    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"SearchStringTooltip"
                                   inManagedObjectContext:self.moc];
    NSFetchRequest *request = [NSFetchRequest new];
    [request setEntity:entity];

       for (NSString *name in newTooltips) {

        [request setPredicate:[NSPredicate predicateWithFormat:@"tooltipText = %@", name]]; //like = (=) + time *2(sometimes *3) ofcourse i know i need like.. Its insensitive

        NSInteger count = [self.moc countForFetchRequest:request error:nil]; //But its is very expensive operation expensive
        if (count > 0) {
            continue;
        }

        DBSearchStringTooltip *tooltip = [NSEntityDescription insertNewObjectForEntityForName:@"SearchStringTooltip"
                                                                       inManagedObjectContext:self.moc];
        tooltip.tooltipText = name;
    }


如何才能更便宜地进行存储?可以有超过10 000个工具提示来检查唯一性...我必须全部检查它们。

最佳答案

快速回答,我相信会更有效率。使用以下代码片段而不是循环:

[request setPredicate:[NSPredicate predicateWithFormat:@"tooltipText IN %@", newTooltips]];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:@[@"tooltipText"]];

NSArray* result = [self.moc executeFetchRequest:request error:nil];
NSArray* existingTooltipNames = [result valueForKey:@"tooltipText"];

NSMutableOrderedSet* itemsToAdd = [NSMutableOrderedSet orderedSetWithArray:newTooltips];
[itemsToAdd minusSet:[NSSet setWithArray:existingTooltipNames]];
for (NSString *name in itemsToAdd) {
    DBSearchStringTooltip *tooltip = [NSEntityDescription insertNewObjectForEntityForName:@"SearchStringTooltip" inManagedObjectContext:self.moc];
    tooltip.tooltipText = name;
}

关于ios - 验证ManagedObject,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15529487/

10-11 00:21