我使用完成处理程序在下面有这两个函数。问题在第二个函数的注释中突出显示...为什么result
部分甚至在函数checforViolationStatus()
中的异步调用完成之前就已执行。
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 :(得分:1)
尝试将您的功能更改为此功能,您应该在completion
中调用countObjectsInBackgroundWithBlock
,此方法是异步的。
或者此函数在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)
}
}
}