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

时间:2013-09-10 08:59:45

标签: ios objective-c cocoa-touch filter nsarray

我有一个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 =&lt; 1,Arrow&gt; rhs = A)”

我该怎么做?我想过滤name中'A'的第一个字母的数组。

6 个答案:

答案 0 :(得分:24)

尝试使用以下代码

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

已编辑:

NSPredicate模式应为:

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

答案 1 :(得分: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);

答案 2 :(得分:3)

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

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

答案 3 :(得分: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;

答案 4 :(得分:0)

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

使用此

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

答案 5 :(得分: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"];