我想过滤我的自定义对象。我的自定义对象外观
class Requestlist: NSObject, NSCoding {
let artist: String
let title: String
let id: String
let type: String
init(artist: String, title: String, id: String, type: String) {
self.artist = artist
self.title = title
self.id = id
self.type = type
}
}
但是程序不断崩溃,并带有以下代码:
let textInput = txbSearch.text
let pred = NSPredicate(format: "ANY artist contains[c] %@ OR title contains[c] %@",textInput!)
let filteredArray = (Constants.liveRequestlist as NSArray).filtered(using: pred)
print(filteredArray)
代码在 KeyboardChange 上运行,当键盘输入像实时搜索一样更改时必须更新。我还想搜索艺术家或标题的一部分。(如 SQL Like 运算符(
两个问题:
-
Any
仅适用于关键路径或对多关系。 -
缺少第二个参数(表示第二个
%@
(。let pred = NSPredicate(format: "artist contains[c] %@ OR title contains[c] %@",textInput!, textInput!)
强烈建议使用原生的 Swift filter
API:
let filteredArray = Constants.liveRequestlist.filter{ $0.artist.range(of: textInput!, options: [.caseInsensitive]) != nil
|| $0.title.range(of: textInput!, options: [.caseInsensitive]) != nil }