ios - 用NSObject过滤NSArray

标签 ios objective-c nsarray uisearchbar nspredicate

我想在tableView中使用搜索栏。
我有一个带人的NSArray(NSObject)。在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 - 用NSObject过滤NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35672296/

相关文章:

ios - UIWebView 只给出一个白屏 - Xcode 7

iOS - 当值可以为零时如何处理字符串连接?

ios - 如何将新语言添加到设置包

objective-c - NSArray 的不区分大小写的 indexOfObject

objective-c - 关于 NSMutableArray/NSArray 类簇,可以安全地假设什么?

objective-c - 在 NSArray 中搜索最近的数字

iphone - 将长按手势和拖动手势结合在一起

ios - swift : UIPageControl auto swipe in iOS 9

ios - 在两个 Storyboard之间切换

ios - 谷歌驱动器选项在 IOS10 的 UIDocumentMenuViewController 中不可见