iosnspredicatecloudkitckquery

Query with compare predicate in CloudKit


I have some CKRecords in Cloudkit, the records has two property of int type, which may be called 'cost' and 'price', I want to query records whose 'cost' > 'price', but the application crashed when I write a query like this:

CKQuery *query = [[CKQuery alloc] initWithRecordType:@"MyRecordType" predicate:
[NSPredicate predicateWithFormat:@"cost > price"]];

this is the crash info given by Xcode:

Terminating app due to uncaught exception 'CKException', reason: 'Invalid predicate, Invalid right expression, is not a function expression

Please Help, thanks in advance.


Solution

  • OK,

    Thought some more about this.

    You query all records, but select only two fields; the cost and the price.

    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "Whatever", predicate: predicate)
    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["cost","price"]
    

    Then you do your query [which should be quicker], sort out the records you want and then go get them with publicDB.fetchRecordWithID.

    Yes, I know more than one query, in fact it looks like a lot more, but wait I think there is an answers in WWDC 2015 Tips & Tricks in Cloudkit; Watch the session and you might find something in there too. Here the code to fetch a record, if you have the record ID.

    publicDB.fetchRecordWithID(), completionHandler: {record, error in
    if error != nil {
        println("there was an error \(error)")
    } else {
        NSOperationQueue.mainQueue().addOperationWithBlock {
            self.plasticOne.text = (record.objectForKey("subCategory") as String)
        }
    

    } })

    Sorry I cannot give you more than that without writing the code myself, and if I do that than you end up using my answer, and I sure you're answer is going to be better :)