简体   繁体   中英

Get results from cloudkit-query

First: I'm really new at CloudKit and the "dispatch"-mechanisms.

But I'd like to write a function in swift which will return the query-results as an array. Now my problem is, that the function doesn't wait for the query to finish and so I receive an empty array. There are records in my DB but I don't get it back properly.

So as I said I don't really understand the whole dispatch_async-mechanism etc. I've also read the tutorial on raywenderlich.com about CloudKit but I still don't get, how I can return the array properly.

This is my actual code. I've often seen people using dispatch_async -methods but I really don't understand how they can return my array.

func loadMyShopsCoolAwesome() ->[Shops]{
        let container = CKContainer.defaultContainer()
        var publicDB = container.publicCloudDatabase

        let myQuery = CKQuery(recordType: "Shops", predicate: NSPredicate(value: true))
        var myShops = [MyShops]()

        publicDB.performQuery(myQuery, inZoneWithID: nil) {
            results, error in
            if error != nil {
                println(error)

            } else {
                for record in results{
                    let shop = MyShops(nameElementAt: record.objectForKey("nameElementAt") as Int, nameElementFromSplit: record.objectForKey("nameElementFromSplit") as Int, nameSplitString: record.objectForKey("nameSplitString"), priceElementAt: record.objectForKey("priceElementAt") as Int, priceSplitString: record.objectForKey("priceSplitString"), shopName: record.objectForKey("shopName"), shopURL: record.objectForKey("shopURL"), xPathName: record.objectForKey("xPathName"), xPathPrice: record.objectForKey("xPathPrice"))

                myShops.append(shop)
                }
                return myShops
            }
        }



    }

You should not let your function return data. This way it will only work if you implement a wait mechanism (usually done with semaphores). If you would do that, you would block your app during the data fetch.

Instead you should return void and instead of returning your shops you should call a new function with the shops. There you should continue processing of the shops. So your function will be:

func loadMyShopsCoolAwesome() {
...

And instead of the

return myShops

You should call a new function. something like:

processShops(myShops)

Which would then call a new function that looks like:

func processShops(shops: [Shops]) {
   // do work with shops
   ...
}

Also be aware that this will be called on a background queue. So if you want to do something with the interface you have call that on the main queue like this:

NSOperationQueue.mainQueue().addOperationWithBlock {
      ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM