-1
使用完成處理程序時,我有以下兩個函數。問題在第二個函數的註釋中突出顯示...爲什麼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)")
}
}
}
Downvoted因爲你做完全一樣的錯誤,因爲在你前面的問題,沒有做什麼,我這麼認真在我的答案解釋那裏。 – matt
是的,傻我。是的,你是對的。希望你添加它作爲答案,會標記它。 – user1406716