gpt4 book ai didi

Swift NSPredicate,名字和姓氏 NSCompoundPredicate?

转载 作者:行者123 更新时间:2023-11-30 11:17:16 28 4
gpt4 key购买 nike

在下面的代码中,我使用 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 FinchFinch/哈罗德等。

干杯!

最佳答案

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)

关于Swift NSPredicate,名字和姓氏 NSCompoundPredicate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51629847/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com