【发布时间】:2018-01-03 17:53:33
【问题描述】:
我正在尝试查询联系人领域数据库,但我有一个查询字符串,我需要在谓词中重复它还是有更好的方法?
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)
【问题讨论】:
-
当过滤这样的数据时,很容易迷失在谓词上,因此调试非常困难。我绝对建议您使用
NSCompoundPredicate来组合每个单独的谓词。还要避免像is_Contact == true这样的任何查询,而不是NSPredicate(format: "is_Contact == %@", true)。
标签: ios swift realm nspredicate