iosnspredicatecloudkitckquery

CloudKit compound query (query with OR)


I would like to query CloudKit using OR with two fields. But I can't find a way how to do this. What I did is:

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"(creatorUserRecordID == %@)", userId];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"(toUser == %@)", userId];
NSCompoundPredicate *compPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicate1, predicate2]];
CKQuery *query = [[CKQuery alloc] initWithRecordType:@"Message" predicate:compPredicate];

But unfortunately CKQuery does not support OR query (as written in documentation) Can I achieve this effect some other way?


Solution

  • CKQuery supports AND and NOT, so you would imagine you could use simple boolean algebra to create a query based on the fact that NOT(NOT A AND NOT B) == A OR B. HOWEVER, the documentation specifically says:

    "The NOT compound operator is not supported in the following cases:

    You cannot use it to negate an AND compound predicate."

    So you must query for each of the ORed predicates separately save them each as a SET and then take the intersection of the two sets to get the final result