我想过滤自定义对象。我的自定义对象看起来
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运算符一样)
答案 0 :(得分:2)
两个问题:
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 }