Limit the amount of results returned in CloudKit

一笑奈何 提交于 2019-12-18 16:34:10

问题


Is there any way to limit the amount of results that are returned in a CKQuery?

In SQL, it is possible to run a query like SELECT * FROM Posts LIMIT 10,15. Is there anything like the last part of the query, LIMIT 10,15 in CloudKit?

For example, I would like to load the first 5 results, then, once the user scrolls down, I would like to load the next 5 results, and so on. In SQL, it would be LIMIT 0,5, then LIMIT 6,10, and so on.

One thing that would work is to use a for loop, but it would be very intensive, as I would have to select all of the values from iCloud, and then loop through them to figure out which 5 to select, and I'm anticipating there to be a lot of different posts in the database, so I would like to only load the ones that are needed.

I'm looking for something like this:

var limit: NSLimitDescriptor = NSLimitDescriptor(5, 10)
query.limit = limit

CKContainer.defaultContainer().publicCloudDatabase.addOperation(CKQueryOperation(query: query)
//fetch values and return them

回答1:


You submit your CKQuery to a CKQueryOperation. The CKQueryOperation has concepts of cursor and of resultsLimit; they will allow you to bundle your query results. As described in the documentation:

To perform a new search:

1) Initialize a CKQueryOperation object with a CKQuery object containing the search criteria and sorting information for the records you want.

2) Assign a block to the queryCompletionBlock property so that you can process the results and execute the operation.

If the search yields many records, the operation object may deliver a portion of the total results to your blocks immediately, along with a cursor for obtaining the remaining records. If a cursor is provided, use it to initialize and execute a separate CKQueryOperation object when you are ready to process the next batch of results.

3) Optionally configure the return results by specifying values for the resultsLimit and desiredKeys properties.

4) Pass the query operation object to the addOperation: method of the target database to execute the operation against that database.

So it looks like:

var q   = CKQuery(/* ... */)
var qop = CKQueryOperation (query: q)

qop.resultsLimit = 5
qop.queryCompletionBlock = { (c:CKQueryCursor!, e:NSError!) -> Void in
  if nil != c {
    // there is more to do; create another op
    var newQop = CKQueryOperation (cursor: c!)
    newQop.resultsLimit = qop.resultsLimit
    newQop.queryCompletionBlock = qop.queryCompletionBlock

    // Hang on to it, if we must
    qop = newQop

    // submit
    ....addOperation(qop)
  }
}

....addOperation(qop)


来源:https://stackoverflow.com/questions/27728115/limit-the-amount-of-results-returned-in-cloudkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!