在下面的代码中,我专门使用NSPredicates,我使用NSCompoundPredicate检查我的搜索功能中是否存在多个不同的参数。我将如何同时使用名字和姓氏进行搜索,我目前正在使用AND,但在UITableView中不返回任何内容。复合谓词中列出的所有其他谓词都很好用。
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
textInSearchField = searchBar.text!
if searchBar.text == ""{
print("Searching for all clients.")
retrieveClients()
view.endEditing(true)
clientTableView.reloadData()
}else{
print("Enter a client name to search.")
isFilteringSearch = true
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let firstAndLast = NSPredicate(format: "firstName = %@ AND lastName = %@", textInSearchField)
let firstNamePredicate = NSPredicate(format: "firstName = %@", textInSearchField)
let lastNamePredicate = NSPredicate(format: "lastName = %@", textInSearchField)
let idPredicate = NSPredicate(format: "id = %@", textInSearchField)
let orPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.or, subpredicates: [firstAndLast,firstNamePredicate, lastNamePredicate, idPredicate])
clientsEntity.predicate = orPredicate
clients = try! context.fetch(clientsEntity) as! [NSManagedObject]
view.endEditing(true)
clientTableView.reloadData()
}
}
需要记住的是,我仍然需要能够使用 LogicalType.or ,因为我想让用户选择按名字,姓氏进行搜索,还可以按以下两种方式进行组合,例如 Harold Finch 或 Finch / Harold 等。
干杯!
答案 0 :(得分:0)
let firstAndLast = NSPredicate(format: "firstName = %@ AND lastName = %@", textInSearchField)
let firstNamePredicate = NSPredicate(format: "firstName = %@", textInSearchField)
let lastNamePredicate = NSPredicate(format: "lastName = %@", textInSearchField)
let idPredicate = NSPredicate(format: "id = %@", textInSearchField)
let orPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.or, subpredicates: [firstAndLast,firstNamePredicate, lastNamePredicate, idPredicate])
我希望对于orPredicate
,应该改为[firstAndLast, idPredicate]
,但是您没有使它起作用。否则,您需要重新考虑一下,这就是您的orPredicate
当前逻辑:
if ((a == x AND b == x) OR (a == x) OR (b == x) OR (c = x)) {
}
(a == x AND b == x)
没有用。
该行有一个问题:
let firstAndLast = NSPredicate(format: "firstName = %@ AND lastName = %@", textInSearchField)
您有两个占位符(%@
),但只有一个参数(textInSearchField
)。
let firstAndLast = NSPredicate(format: "firstName = %@ AND lastName = %@", textInSearchField, textInSearchField)
答案 1 :(得分:0)
感谢您的帮助,我最终在 contains [c] 中使用了另一种方法,下面的代码供任何需要类似功能帮助的人使用,您可以使用contains [c](contains字符)以通过字符进行搜索,这特别适用于所有字符串,例如名字或姓氏,在我的情况下也适用于存储为字符串的ID。
loop_cond = lambda a1, b1, idx_var: tf.less(idx_var, n_inodes)
loop_vars = [inode_h, inode_c, idx_var]
inode_h, inode_c, idx_var = tf.while_loop(loop_cond, _recurrence, loop_vars,
shape_invariants=[tf.TensorShape([None, self.hidden_dim]),
tf.TensorShape([None, self.hidden_dim]),
idx_var.get_shape()]
}
我关注了此帖子NSPredicate: Combine CONTAINS with IN的第二个答案
谢谢