完成处理程序不能按预期的方式在Swift中工作

问题描述:

使用完成处理程序时,我有以下两个函数。问题在第二个函数的注释中突出显示...为什么result部分甚至在功能checforViolationStatus()中的异步调用完成之前得到执行。完成处理程序不能按预期的方式在Swift中工作

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)") 

     } 
    } 


} 
+0

Downvoted因为你做完全一样的错误,因为在你前面的问题,没有做什么,我这么认真在我的答案解释那里。 – matt

+0

是的,傻我。是的,你是对的。希望你添加它作为答案,会标记它。 – user1406716

试着改变你的函数,你应该在countObjectsInBackgroundWithBlock调用completion,这种方法是异步。

或者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) 

    } 
} 
}