Evaluating an NSPredicate on a NSArray (without filtering)

爷,独闯天下 提交于 2019-11-30 07:16:43
EmptyStack

Use the SIZE operator of NSPredicate which is equivalent to count method of NSArray.

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF[SIZE] == 3"];
NSArray *list = [NSArray arrayWithObjects:@"uno", @"dos", @"volver", nil];
BOOL match = [pred evaluateWithObject:list];
Dave DeLong

An alternative to using [SIZE] in your predicate format string is to do this:

NSPredicate *p = [NSPredicate predicateWithFormat:@"@count = 3"];

@count is one of the simple collection keypath operators and is quite useful. It is far more common to use it than [SIZE], although both are fine.

For example, you can create category with methods you need:

@interface NSPredicate (myCategory)
    - (BOOL)evaluateWithArray:(id)array;
    // other methods
@end

and in .m file implement it like this:

- (BOOL)evaluateWithArray:(id)array {
    if ([array isKindOfClass:[NSArray class]])
        return [self evaluateWithObject:array];
    return NO;
}

Hope, it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!