阅读背景:

CloudKit API响应时间慢?

来源:互联网 

I have made a simple app for interacting with a CloudKit database. Essentially it's just a date picker and two buttons, the first adding a new record with the set time to the database, and the second retrieving all the records. This seems to work fine except that all operations are extremely slow. It takes around 10 seconds to get a response from both saveRecord and performQuery. What am I doing wrong? Below is the code from retrieving records.

我已经制作了一个与CloudKit数据库交互的简单应用程序。基本上它只是一个日期选择器和两个按钮,第一个添加一个新的记录,设置时间到数据库,第二个检索所有记录。这似乎工作正常,但所有操作都非常慢。从saveRecord和performQuery获取响应大约需要10秒钟。我究竟做错了什么?以下是检索记录的代码。

@IBAction func retreiveButtonClick(sender: AnyObject) {
    self.labelOutlet.text = "Waiting..."

    func myHandler(results:[AnyObject]!, error:NSError!) {
        if let err = error {
            println("err: \(err.localizedDescription)")
        } else {
            self.labelOutlet.text = "Got \(results.count) results:"
            for record in results {
                let time = record.objectForKey("testTime") as NSDate
                self.labelOutlet.text = self.labelOutlet.text + "\n\(time.description)"
            }
        }
    }

    var query = CKQuery(recordType:"TestTable", predicate:NSPredicate(value:true))
    cloudDatabase.performQuery(query, inZoneWithID: nil, myHandler)   
}

I am testing this on my iPhone 5, which is connected to the local WiFi. I have noticed that saved records show up in CloudKit Dashboard long before the completion handler is called (which I have plenty of time to check), so I suspect I have done something wrong in my code.

我正在我的iPhone 5上测试它,它连接到本地WiFi。我注意到保存的记录在调用完成处理程序之前很久就出现在CloudKit Dashboard中(我有足够的时间来检查),所以我怀疑我在代码中做错了。

2 个解决方案

#1


6  

Your handler will be called in a background thread. You should perform all UI manipulations on the main thread. You could put all your myHandler code within a block like:

您的处理程序将在后台线程中调用。您应该在主线程上执行所有UI操作。您可以将所有myHandler代码放在一个块中,如:

func myHandler(results:[AnyObject]!, error:NSError!) {
NSOperationQueue.mainQueue().addOperationWithBlock({
        // ... put here your function code.
    })
}

It could be that other code is executing on the main queue that could hold up execution of this code. Make sure you execute long lasting code on a background queue.

可能是其他代码正在主队列上执行,可能会阻止执行此代码。确保在后台队列上执行持久代码。

Besides that there is nothing wrong with your code.

除此之外,您的代码没有任何问题。

#2


3  

Adding to Edwin's answer...

加入Edwin的回答......

I agree it looks like you are trying to update the UI on a background thread.

我同意您似乎正在尝试在后台线程上更新UI。

If you want to avoid the NSOperationQueue complexity...you could...in ObjectiveC

如果你想避免NSOperationQueue的复杂性......你可以......在ObjectiveC中

dispatch_async(dispatch_get_main_queue(), ^{
     //...update code 
});

分享到: