具有许多条件和一个论证的谓词

时间:2018-01-03 17:53:34

标签: ios swift realm nspredicate

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

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)

1 个答案:

答案 0 :(得分:1)

由于您的谓词看起来相同并且只显示属性名称的差异,我建议创建一个属性名称数组。然后,您可以通过循环名称为每个名称创建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数组,可以非常轻松地删除或添加单个属性到谓词。它也更具可读性,因为所有属性都在一行中定义,而不是在整个地方定义。