Reputation: 917
I'm trying to filter an array of customs objects by the first letter of a property called "name". To achieve this I made an Array of first letters:
_lettersArray = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];
I want to save the results in a NSDictionary where the key is the First letter and the object an Array of objects with the first letter of the property name the key:
for (NSString* letter in _lettersArray) {
NSPredicate* letterPredicate = [NSPredicate predicateWithFormat:@"name beginswith[c] '%@'", letter];
NSArray* itemsLetter = [_items filteredArrayUsingPredicate:letterPredicate];
[_letters setObject:itemsLetter forKey:letter];
}
But when this algorithm ends the _letters dictionary have all the keys but the objects are empty arrays. I have tried to change the
NSPredicate* letterPredicate = [NSPredicate predicateWithFormat:@"name beginswith[c] '%@'", letter];
for
NSPredicate* letterPredicate = [NSPredicate predicateWithFormat:@"name beginswith[c] 'B'"];
And all works fine(Of course it gives me only the objects that starts with B). What I'm doing wrong? For me it's clear that the problem is in the predicate instruction. I have see that _lettersArray is fine and it is and I tried to use [letter characterAtIndex:0]
instead of letter but gives me the same result...
An NSLog of the predicate sentence gives me the exact sentence formation that I do manually and works!
Upvotes: 0
Views: 354
Reputation: 857
From the Predicate Programming Guide:
Single or double quoting variables (or substitution variable strings) cause %@, %K, or $variable to be interpreted as a literal in the format string and so prevent any substitution.
So try taking the quotes off of '%@':
NSPredicate* letterPredicate = [NSPredicate predicateWithFormat:@"name beginswith[c] %@", letter];
Upvotes: 2