【问题标题】:NSPredicate for multiple matches in NSFetchRequestNSPredicate 用于 NSFetchRequest 中的多个匹配项
【发布时间】:2013-08-30 22:08:02
【问题描述】:

首先:对不起,如果标题不是很清楚,我无法将我的问题用简短的语言表达出来!

请考虑以下情况:
- 您正在使用 Core Data 来存储对象
- 你想从你的上下文中获取对象
- 您想包含一个谓词以仅获取具有某些属性的对象
- 您有一个包含键值对的 NSDictionary,其中键代表属性名称,值代表要匹配的所需值

如何最好地实现这一目标?

我目前有以下方法,这是实现此目的的一种快速且可能效率低下的方法:

NSDictionary *attributes = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:@"value1", @"value2", nil] forKeys: [NSArray arrayWithObjects:@"attr1", @"attr2", nil] ];

// Build predicate format
NSString *predicate = @"";
NSMutableArray *predicateArguments = [[NSMutableArray alloc] init];
int index = 0;
for (NSString *key in attributes) {
    NSString *value = [attributes objectForKey: key];
    predicate = [predicate stringByAppendingFormat: @"(%@ = %@) %@", key, @"%@", index == [attributes count]-1 ? @"" : @"AND "];
    [predicateArguments addObject: value];
    index++;
}

NSPredicate *matchAttributes = [NSPredicate predicateWithFormat:predicate argumentArray:predicateArguments];

--

是否有更短或更有效的方法来实现这个谓词?

请注意,由于不支持 NSFetchRequest(核心数据),因此块谓词不是一个选项

【问题讨论】:

    标签: ios cocoa-touch core-data nspredicate


    【解决方案1】:

    一个稍微短一些,也许更优雅的方法是使用NSCompoundPredicate

    NSDictionary *attributes = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:@"value1", @"value2", nil] forKeys: [NSArray arrayWithObjects:@"attr1", @"attr2", nil] ];
    
    // Build array of sub-predicates:
    NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
    for (NSString *key in attributes) {
        NSString *value = [attributes objectForKey: key];
        [subPredicates addObject:[NSPredicate predicateWithFormat:@"%K = %@", key, value]];
    }
    // Combine all sub-predicates with AND:
    NSPredicate *matchAttributes = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
    

    添加:更好(感谢 Paul.s):

    NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
    [attributes enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        [subPredicates addObject:[NSPredicate predicateWithFormat:@"%K = %@", key, value]];
    }];
    NSPredicate *matchAttributes = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
    

    【讨论】:

    • 您可以使用块编号 [attributes enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { [subPredicates addObject:[NSPredicate predicateWithFormat:@"%K = %@", key, value]]; }]; 稍微缩短(1 行)并且很可能更高效
    • 感谢您的解决方案,非常有帮助。我将 Paul.s 的评论复制到未来观众的答案中,以防他们错过评论!
    猜你喜欢
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2011-10-28
    • 2015-08-30
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多