Filter array by first letter of string property
37,388
Solution 1
Try with following code
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF like %@", yourName];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];
EDITED :
NSPredicate
pattern should be:
NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];
Solution 2
Here is one of the basic use of NSPredicate for filtering array .
NSMutableArray *array =
[NSMutableArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", @"arbind", nil];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'b'"];
NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
NSLog(@"beginwithB = %@",beginWithB);
Solution 3
NSArray offers another selector for sorting arrays:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Person *first, Person *second) {
return [first.name compare:second.name];
}];
Solution 4
If you want to filter array take a look on this code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", @"qwe"];
NSArray *result = [self.categoryItems filteredArrayUsingPredicate:predicate];
But if you want to sort array take a look on the following functions:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context;
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint;
- (NSArray *)sortedArrayUsingSelector:(SEL)comparator;
Author by
Nubaslon
Russian SWift/Objective-C developer, iPhone, iPad, iOS Developer (sorry for my English ;)
Updated on August 30, 2020Comments
-
Nubaslon over 3 years
I have an
NSArray
with objects that have aname
property.I would like filter the array by
name
NSString *alphabet = [agencyIndex objectAtIndex:indexPath.section]; //---get all states beginning with the letter--- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet]; NSMutableArray *listSimpl = [[NSMutableArray alloc] init]; for (int i=0; i<[[Database sharedDatabase].agents count]; i++) { Town *_town = [[Database sharedDatabase].agents objectAtIndex:i]; [listSimpl addObject:_town]; } NSArray *states = [listSimpl filteredArrayUsingPredicate:predicate];
But I get an error - "Can't do a substring operation with something that isn't a string (lhs = <1, Arrow> rhs = A)"
How can I do this? I would like to filter the array for the first letter in
name
being 'A'.