gpt4 book ai didi

ios - 具有多个条件和一个参数的谓词

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

我正在尝试查询联系人 Realm 数据库,但我有一个查询字符串,我是否需要在谓词中重复它,或者有更好的方法吗?

let contactResults = realm.objects(ContactRealm.self).filter("is_Contact == true AND full_name CONTAINS[c] %@ OR phone_number_one CONTAINS[c] %@ OR phone_number_two CONTAINS[c] %@ OR phone_number_three CONTAINS[c] %@ OR email_address_one CONTAINS[c] %@ OR email_address_two CONTAINS[c] %@", query, query, query, query, query, query).sorted(byKeyPath: "full_name", ascending: true)

这样的查询也被认为是一种不好的做法吗?

更新:正如此处评论所建议的:

let predicateContact = NSPredicate(format: "is_Contact == true")

let fullname = NSPredicate(format: "full_name CONTAINS[c] %@", query)

let phoneNumber = NSPredicate(format: "phone_number_one CONTAINS[c] %@", query)

let phonenumbertwo = NSPredicate(format: "phone_number_one CONTAINS[c] %@", query)

let email = NSPredicate(format: "phone_number_one CONTAINS[c] %@", query)

let secondEmail = NSPredicate(format: "phone_number_one CONTAINS[c] %@", query)

let compoundOr = NSCompoundPredicate(orPredicateWithSubpredicates: [fullname, phoneNumber, phonenumbertwo, email, secondEmail])

let compound = NSCompoundPredicate(type: .and, subpredicates: [predicateContact, compoundOr])

let contactResults = realm.objects(ContactRealm.self).filter(compound).sorted(byKeyPath: "full_name", ascending: true)

最佳答案

由于您的谓词看起来相同并且仅在属性名称方面有所不同,因此我建议创建一个属性名称数组。然后,您可以通过遍历名称为每个名称创建一个 NSPredicate

let attributes = ["full_name", "phone_number_one", "phone_number_two", "phone_number_three", "email_address_one", "email_address_two"]
let contactPredicateArray = parameters.map {
NSPredicate("\($0) CONTAINS[c] %@", query)
}
let contactPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: contactPredicateArray)
let isContactPredicte = NSPredicate(format: "is_Contact == %@", true)
let predicate = NSCompoundPredicate(type: .and, subpredicates: [isContactPredicte, contactPredicate])

这样,代码更加灵活,因为通过修改 attributes 数组可以非常轻松地为谓词删除或添加单个属性。它也更具可读性,因为所有属性都在一行中定义,而不是到处都是。

关于ios - 具有多个条件和一个参数的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48082639/

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