简体   繁体   English

Swift,parse.com:如何从查询传递数据

[英]Swift, parse.com: how to pass data from query

I have such query to parse.com. 我对parse.com有这样的查询。 Why the numObjects variable has different values ​​inside the findObjectsInBackgroundWithBlock and on the function exits 为什么numObjects变量在findObjectsInBackgroundWithBlock内部和函数退出时具有不同的值

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
}

Instead of using findObjectsInBackgroundWithBlock which runs asynchronously, try using findObjects which runs synchronously: 而不是使用的findObjectsInBackgroundWithBlock其中异步运行,尝试使用findObjects它运行同步:

//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.
    }
}

That's the nature of async code, your function will run the outer code to completion, then some time later (depending on connection speed and query complexity) the completion block will run. 这就是异步代码的本质,您的函数将运行外部代码直至完成,然后过一会儿(取决于连接速度和查询复杂性),将运行完成代码块。

Your calling code should do something like the following: 您的调用代码应执行以下操作:

  • create the query 创建查询
  • start the query with a completion block 从完成块开始查询
  • show a loading animation 显示加载动画
  • return (query results still unknown) 返回(查询结果仍然未知)

Then you should think about the inside of the block: 然后,您应该考虑一下该块的内部:

  • check for errors 检查错误
  • update values that the UI is bound to 更新UI绑定到的值
  • tell the UI to refresh 告诉用户界面刷新

You can't have a function that will return the count, but you could write a function that takes a completion block as a parameter, and executes it in the query completion block. 您没有可以返回计数的函数,但是您可以编写一个将完成块作为参数并在查询完成块中执行的函数。 That's a bit more advanced though. 不过,这有点高级。

query.findObjectsInBackgroundWithBlock is will be executed asynchronously , the completion block is called after fetching objects. query.findObjectsInBackgroundWithBlock将异步执行,在获取对象后调用完成块。 therefore the code after the block called first hence numObjects value is 0. 因此,第一个调用的块之后的代码因此numObjects值为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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