本文介绍了按字符串属性的第一个字母过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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(lhs =< 1,Arrow> rhs = A)

But I get an error - "Can't do a substring operation with something that isn't a string (lhs = <1, Arrow> rhs = A)"

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

How can I do this? I would like to filter the array for the first letter in name being 'A'.

推荐答案

尝试以下代码

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

已编辑

NSPredicate 模式应为:

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

这篇关于按字符串属性的第一个字母过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:46