【问题标题】:Filter NSArray with NSObject inside过滤带有 NSObject 的 NSArray
【发布时间】:2016-02-27 16:31:12
【问题描述】:

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

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

对于 searchBar 这个代码:

- (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 = )'

【问题讨论】:

    标签: ios objective-c nsarray uisearchbar nspredicate


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢韦恩!我会尝试循环播放它。 :)
    猜你喜欢
    • 2014-03-26
    • 2013-11-20
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2013-01-04
    相关资源
    最近更新 更多