16

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

我想过滤数组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];

但我得到一个错误 - “不能对不是字符串的东西进行子字符串操作(lhs = <1,Arrow> rhs = A)”

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

4

6 回答 6

24

尝试使用以下代码

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

编辑:

NSPredicate模式应该是:

NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];
于 2013-09-10T09:19:25.823 回答
10

这是 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);
于 2014-09-09T07:20:34.403 回答
3

NSArray 提供了另一个排序数组的选择器:

NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Person *first, Person *second) {
    return [first.name compare:second.name];
}];
于 2013-09-10T09:05:12.537 回答
1

如果要过滤数组,请查看以下代码:

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

但是,如果您想对数组进行排序,请查看以下函数:

- (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;
于 2013-09-10T09:18:33.617 回答
0

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

用这个

[listArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
于 2013-09-10T09:09:03.897 回答
0

签出这个库

https://github.com/BadChoice/Collection

它带有许多简单的数组函数,再也不用写循环了

所以你可以做

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

这仅获取以字母顺序排序的以 A 开头的文本

如果您使用对象执行此操作:

NSArray* result = [thArray filter:^BOOL(AnObject *object) {
    return [[object.name substr:0] isEqualToString:@"A"]; 
}] sort:@"name"];
于 2016-08-29T18:01:53.417 回答