Tuesday, October 27, 2009

NSPredicate

Here are two examples of elementary usage of NSPredicate. This is good stuff to know: how to do in Cocoa something that is second-nature in Python.

In the first one, we search an array of strings for @"SELF like [c] 'g*'", that is the object is "like" (equals in a stringy way) the string that starts with g and has zero or more letters following, in a [c] case-insensitive comparison.


    NSArray *A = [NSArray arrayWithObjects:
@"Tom",@"Sam",@"George",nil];
NSPredicate *p = [NSPredicate
predicateWithFormat:
@"SELF like [c] 'g*' "];
NSLog(@"%@",
[A filteredArrayUsingPredicate:p]);


 (
George
)


In the second example, we have an array of dictionaries and test them for any that have an object for the key "firstName" that is contained in an array (which is derived from same array we used above). Since we eliminated the last dictionary (range from 0 up to but not including 2), only the first two dictionaries pass the filter, as shown in the output:


    NSMutableArray *mA;
mA = [NSMutableArray arrayWithCapacity:5];
NSMutableDictionary* mD;
for (id obj in A) {
mD = [NSMutableDictionary
dictionaryWithObject:obj forKey:@"firstName"];
[mA addObject:mD];
}

NSIndexSet *is = [NSIndexSet
indexSetWithIndexesInRange:
NSMakeRange(0,2) ];
NSArray *A2 = [A objectsAtIndexes:is];

p = [NSPredicate
predicateWithFormat: @"firstName in %@", A2];
NSLog(@"%@",
[mA filteredArrayUsingPredicate:p]);


(
{
firstName = Tom;
},
{
firstName = Sam;
}
)

No comments: