NSPredicate 在一些空的数组上

Dan*_*Dan 4 arrays objective-c nspredicate ios swift

我正在尝试过滤包含 Bird 类型的核心数据实体的数组数组。实体已根据带有部分和行的 UITableView 拆分为数组数组。

要搜索,我有以下方法基于这个问题NSPredicate on arrays

func filterContentForSearchText(searchText: String) {
    let resultPredicate = NSPredicate(format: "SELF[0].common_name contains[cd] %@", searchText)
    self.filteredBirds = self.birds.filteredArrayUsingPredicate(resultPredicate!)
}
Run Code Online (Sandbox Code Playgroud)

然而,这会导致错误

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
Run Code Online (Sandbox Code Playgroud)

这可能是有道理的,因为数组有 27 个 (AZ, #) 元素,其中一些元素没有实体

那么,如何调整 NSPredicate 查询以考虑某些数组可能为空?

Oni*_* IV 5

 let resultPredicate = NSPredicate(format: "SELF.@count >0  AND SELF[0].common_name contains[cd] %@", searchText)
Run Code Online (Sandbox Code Playgroud)