按string属性的第一个字母过滤数组

我有一个具有name属性的对象的NSArray

我想按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]; 

但是,我得到一个错误 – “不能做一个string的操作不是一个string(lhs = <1,箭头> rhs = A)”

我怎样才能做到这一点? 我想过滤name “A”的第一个字母的数组。

尝试使用以下代码

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

编辑:

NSPredicate模式应该是:

 NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet]; 

这是NSPredicate过滤数组的基本用法之一。

 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); 

NSArray提供了另一个sorting数组的select器:

 NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Person *first, Person *second) { return [first.name compare:second.name]; }]; 

如果你想过滤数组看看这个代码:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", @"qwe"]; NSArray *result = [self.categoryItems filteredArrayUsingPredicate:predicate]; 

但是如果你想数组进行sorting,请看下面的函数:

 - (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; 

请访问https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html

用这个

 [listArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 

结帐这个库

https://github.com/BadChoice/Collection

它带有许多简单的数组函数,永远不会再写一个循环

所以你可以做

 NSArray* result = [thArray filter:^BOOL(NSString *text) { return [[name substr:0] isEqualToString:@"A"]; }] sort]; 

这只能得到以A开始的文本按字母顺序sorting

如果你正在做的对象:

 NSArray* result = [thArray filter:^BOOL(AnObject *object) { return [[object.name substr:0] isEqualToString:@"A"]; }] sort:@"name"];