如何在 CoreData iOS 谓词生成器中多次传递相同的参数?
How to pass the same parameter multiple times in CoreData iOS predicate builder?
我有一个 UITableView
和一个 UISearchbar
,让我可以根据 UISearchbar
中的 search text
过滤数据。
CoreData
table包含3 attributes
name, notes, date
我想根据 User
搜索文本在三列中搜索任何匹配项。
所以我试了一下:
let searchText = searchText.lowercased()
let query = "name contains[cd] %@ OR notes contains[cd] %@ OR date contains[cd] %@"
let predicate = NSPredicate(format: query, searchText, searchText, searchText)
有什么方法可以一次性传递相同的参数(searchText
)?
类似于Java
字符串格式化程序:
let query = "name contains[cd] %1$@ OR notes contains[cd] %1$@ OR date contains[cd] %1$@"
let predicate = NSPredicate(format: query, searchText)
您可以使用替代变量:
let searchText = searchText.lowercased()
let template = NSPredicate(format: "name contains[cd] $SRCH OR notes contains[cd] $SRCH OR date contains[cd] $SRCH")
let subVars = ["SRCH": searchText]
let predicate = template.withSubstitutionVariables(subVars)
参见 Apple Documentation 中的 "Creating Predicates using Predicate Templates"。
我有一个 UITableView
和一个 UISearchbar
,让我可以根据 UISearchbar
中的 search text
过滤数据。
CoreData
table包含3 attributes
name, notes, date
我想根据 User
搜索文本在三列中搜索任何匹配项。
所以我试了一下:
let searchText = searchText.lowercased()
let query = "name contains[cd] %@ OR notes contains[cd] %@ OR date contains[cd] %@"
let predicate = NSPredicate(format: query, searchText, searchText, searchText)
有什么方法可以一次性传递相同的参数(searchText
)?
类似于Java
字符串格式化程序:
let query = "name contains[cd] %1$@ OR notes contains[cd] %1$@ OR date contains[cd] %1$@"
let predicate = NSPredicate(format: query, searchText)
您可以使用替代变量:
let searchText = searchText.lowercased()
let template = NSPredicate(format: "name contains[cd] $SRCH OR notes contains[cd] $SRCH OR date contains[cd] $SRCH")
let subVars = ["SRCH": searchText]
let predicate = template.withSubstitutionVariables(subVars)
参见 Apple Documentation 中的 "Creating Predicates using Predicate Templates"。