简体   繁体   English

完成处理程序在 Swift 中没有按预期工作

[英]Completion handler not working as expected in Swift

I have these two functions below, using a completion handler.我在下面有这两个函数,使用完成处理程序。 The questions is highlighted in comments of the 2nd function... why is the result part getting executed even before the asynchronous call in function checforViolationStatus() been completed.问题在第二个函数的注释中突出显示......为什么即使在函数checforViolationStatus()的异步调用完成之前, result部分也会被执行。

func checkViolationStatus(usr: PFUser, completion: (result: Int32) -> Void) {
    var violations: Int32 = 0
    var query = PFQuery(className: PF_BLOCKEDUSERS_CLASS_NAME)
    query.whereKey(PF_BLOCKEDUSERS_USER, equalTo: usr)


    query.countObjectsInBackgroundWithBlock {
        (count: Int32, error: NSError?) -> Void in
        if error == nil {
            print("Result = \(count)")

            //The result here returned is 4, I can see it but always ZERO(0) gets printed in the main function. Unable to understand why.
            violations = count
        }
    }

    completion(result: violations)

}


    func goToMainMenu() {

    if PFUser.currentUser() != nil {

        self.mCould.checkViolationStatus(PFUser.currentUser()!) {
            (result: Int32) in

            //QUESTION: result is getting returned as ZERO even before the actual asynchronous call in the checkforViolation function has been completed - why????

            if result < 4 {
                //Go to Main Menu Screen
                print("result<=4 so calling segue")
                self.performSegueWithIdentifier("segueLoginVCToMainVC", sender: nil)
            } else {
                print("result >=4, so should not be doing anything")
            }

            print("Number of Violations Received Back: \(result)")

        }
    }


}

Try change your function to this,you should call completion in the countObjectsInBackgroundWithBlock ,this method is async.尝试将您的功能更改为此,您应该在countObjectsInBackgroundWithBlock调用completion ,此方法是异步的。

Or this function return before countObjectsInBackgroundWithBlock is finished或者这个函数在countObjectsInBackgroundWithBlock完成之前返回

func checkViolationStatus(usr: PFUser, completion: (result: Int32) -> Void) {
var violations: Int32 = 0
var query = PFQuery(className: PF_BLOCKEDUSERS_CLASS_NAME)
query.whereKey(PF_BLOCKEDUSERS_USER, equalTo: usr)


query.countObjectsInBackgroundWithBlock {
    (count: Int32, error: NSError?) -> Void in
    if error == nil {
        print("Result = \(count)")

        //The result here returned is 4, I can see it but always ZERO(0) gets printed in the main function. Unable to understand why.
        violations = count
        completion(result: violations)

    }
}
}

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

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