Nubaslon Nubaslon - 1 year ago 83
Objective-C Question

Filter array by first letter of string property

I have an

with objects that have a

I would like filter the array by

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
being 'A'.

Answer Source

Try with following code

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF like %@", yourName];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];


NSPredicate pattern should be:

NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download