阅读背景:

将NSPredicate / NSCompoundPredicate与Where子句或Optional Return,CloudKit一起使用

来源:互联网 

Not sure if the subject line makes sense, I have an NSCompoundPredicate which is working great, it query's date within 24 hours, if record is "blocked", and also only returns records of my custom "type".

不确定主题行是否有意义,我有一个非常好的NSCompoundPredicate,它在24小时内查询日期,如果记录被“阻止”,并且只返回我自定义“类型”的记录。

What I mean by custom type is the value can either be a 1, 2, or 3. So i want my query to return those of types 2 and 3, which works. However, for the fancy part when there is a 3, there also will be a string value under "User Names" value in the cloud kit database. Under type 2, the user name will be blank.

我的意思是自定义类型的值可以是1,2或3.所以我希望我的查询返回类型2和3的那些,这是有效的。但是,对于有3的奇特部分,云工具包数据库中的“用户名”值下也会有一个字符串值。在类型2下,用户名将为空。

So i want to return all type 3's with a user name of "Smith" then also all type 2's with no user name at all. I am having trouble getting both the type 2's and the 3's with a user name of smith, the way i have it it only returns users with name smith and doesn't return any type 2's. Need a way to have the UserName predicate be optional?

所以我想返回所有类型3的用户名为“Smith”,然后所有类型2都没有用户名。我无法使用用户名smith获取类型2和3的类型,我拥有它的方式它只返回名称为smith的用户,并且不返回任何类型2的。需要一种方法让UserName谓词是可选的吗?

Code:

let predName = NSPredicate(format: "UserName CONTAINS %@", "Smith")
let customTypes = [2, 3]
let time = 86400
let fromDateDay: Double = (NSDate().timeIntervalSinceReferenceDate - time)
let predDate = NSPredicate(format: "date >= %f", fromDateDay)
let predBlocked = NSPredicate(format: "blocked != %d", 1)
pred = NSCompoundPredicate(andPredicateWithSubpredicates: [customTypes, predDate, predBlocked, predName])

1 个解决方案

#1


1  

First, customTypes is not a predicate, so your code as posted should crash. You need to construct a predicate that takes into account the difference between custom type 2 and 3.

首先,customTypes不是谓词,因此您发布的代码应该崩溃。您需要构建一个谓词,该谓词考虑了自定义类型2和3之间的差异。

NSPredicate(format: 
 "(customType = 2 && userName contains %@) || (customType = 3)", "Smith")

分享到: