Swift,parse.com:如何从查询中传递数据 [英] Swift, parse.com: how to pass data from query

查看:104
本文介绍了Swift,parse.com:如何从查询中传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对parse.com有这样的疑问。
为什么numObjects变量在findObjectsInBackgroundWithBlock和函数出口中有不同的值

I have such query to parse.com. Why the numObjects variable has different values ​​inside the findObjectsInBackgroundWithBlock and on the function exits

func searchUserInParse () -> Int {

    var numObjects : Int = 0 // the num return objects from query

    var query = PFQuery(className:"Bets")
    query.whereKey("user", equalTo: "Bob")
    query.findObjectsInBackgroundWithBlock {
        (objects: AnyObject[]!, error: NSError!) -> Void in
        if !error {
            numObjects = objects.count
            println(numObjects) // at this point the value = 1
        } else {
            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo)
        }
    }
    println(numObjects) // at this point the value = 0

    return numObjects
}


推荐答案

不使用异步运行的 findObjectsInBackgroundWithBlock ,而是尝试使用同步运行的 findObjects

Instead of using findObjectsInBackgroundWithBlock which runs asynchronously, try using findObjects which runs synchronously:

//Set up query...
var objects = query.findObjects()
numObjects = objects.count
println(numObjects)

然后在运行你的函数时,这样做:

Then when running your function, do it like so:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) {
    //Search users
    searchUserInParse()

    dispatch_async(dispatch_get_main_queue()) {
        //Show number of objects etc.
    }
}

这篇关于Swift,parse.com:如何从查询中传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆