用里面的 NSObject 过滤 NSArray

Filter NSArray with NSObject inside

我想在我的 tableView 中使用搜索栏。 我有一个带有 Person (NSObject) 的 NSArray。在 cellForRow 中,我正在使用此代码:

Person *person = [[self.sectionedPersonName objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = person.fullName;

对于搜索栏,此代码:

- (void)searchForText:(NSString *)searchText {
    if (searchText.length > 0) {
        searchBar = YES;
    } else {
        searchBar = NO;
    }
        NSLog(@"%@", self.sectionedPersonName);
        NSPredicate *predicate; = [NSPredicate predicateWithFormat:@"SELF.fullName beginswith[c] %@", searchText];
        self.searchResults = [self.sectionedPersonName filteredArrayUsingPredicate:predicate];
}

self.sectionedPersonName 包含这个:

(
        (
        "<Person: 0x7fc0f6012650>"
    ),
        (
    ),
        (
    ),
        (
        "<Person: 0x7fc0f600f8a0>",
        "<Person: 0x7fc0f60132e0>"
    ),
        (
    ),
        (
    ),
        (
    ),
        (
        "<Person: 0x7fc0f6012d80>"
    ),
        (
    ),
        (
        "<Person: 0x7fc0f6012b30>"
    ),
        (
        "<Person: 0x7fc0f6010100>"
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    ),
        (
    )
)

所以我的问题是如何在此基础上创建 NSPredicate? 我试过这个,但不起作用:

NSPredicate *predicate; = [NSPredicate predicateWithFormat:@"SELF.fullName beginswith[c] %@", searchText];

错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = (
    "Anna Haro"
) rhs = )'

你不是人山人海,而是人山人海。因此,您不能简单地过滤数组,因为您所有的比较实际上都是在尝试将字符串数组与字符串进行比较。这就是您看到 'strange' 结果和崩溃的原因。

您最好的选择是创建自己的循环以遍历外部数组,然后 运行 您对每个内部数组的谓词。将生成的过滤数组添加到一个新的可变数组中,该数组包含总体结果。