ios - 按字符串属性的首字母过滤数组

标签 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 = <1, Arrow> 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];

关于ios - 按字符串属性的首字母过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18714634/

相关文章:

iphone - 如何使用 UITextInputMode

ios - 未捕获的异常 'NSGenericException : application has presented a UIAlertController of style UIAlertControllerStyleActionSheet

ios - NSString正则表达式查找和替换

iphone - 如何将 iPhone 数据备份到服务器?

ios - 为什么返回 View 时获取的数据不消失?

jquery - 使用 CSS repeat-x 重复多个图像

ios - 扩展中的 Swift 闭包

ios - 在 iOS 上使用 Audio Queue 播放音频一段时间后声音静音

ios - 如何覆盖包含 block 的objC中的方法?

ios - 为什么第二次在 iOS 上执行事件会更快?