Saturday, March 12, 2011

NSPredicate: compound Cocoa example in code

I'm resisting the temptation to call this simple---it's not! All we're doing is filtering an array of dicts for those whose 'value' is neither too large nor too small. I have no idea why it has to be this complicated. The example is from the NSPredicate docs (as reformatted and with renamed vars by me):


#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSArray *A = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObject:[
NSNumber numberWithInt:5] forKey:@"value"],
[NSDictionary dictionaryWithObject:[
NSNumber numberWithInt:50] forKey:@"value"],
[NSDictionary dictionaryWithObject:[
NSNumber numberWithInt:500] forKey:@"value"],
nil];

NSExpression *lhs = [NSExpression
expressionForKeyPath:@"value"];
NSExpression *gtrhs = [NSExpression
expressionForConstantValue:[NSNumber numberWithInt:10]];
NSExpression *ltrhs = [NSExpression
expressionForConstantValue:[NSNumber numberWithInt:100]];

NSPredicate *gtpred;
gtpred = [NSComparisonPredicate
predicateWithLeftExpression:lhs
rightExpression:gtrhs
modifier:NSDirectPredicateModifier
type:NSGreaterThanOrEqualToPredicateOperatorType
options:0];

NSPredicate *ltpred;
ltpred = [NSComparisonPredicate
predicateWithLeftExpression:lhs
rightExpression:ltrhs
modifier:NSDirectPredicateModifier
type:NSLessThanOrEqualToPredicateOperatorType
options:0];

NSPredicate *pred;
pred = [NSCompoundPredicate andPredicateWithSubpredicates:
[NSArray arrayWithObjects:gtpred, ltpred, nil] ];

NSArray *fA = [A filteredArrayUsingPredicate:pred];
for (id obj in fA) {
NSLog(@"%@", [obj description]);
}
return 0;
}

> gcc -o test pred.m -framework Foundation
> ./test
2011-03-12 11:48:31.640 test[70403:903] {
value = 50;
}

No comments: