Below is my function in which I have highlighted the code that works (i.e. asynchronous), but what I want is the synchronous code with PFQuery.countObjects(error: NSErrorPointer)
to work.
//Count how many violations User has.
func checkViolationStatus(usr: PFUser) -> Int32 {
var violations: Int32 = 0
var query = PFQuery(className: PF_BLOCKEDUSERS_CLASS_NAME)
query.includeKey(PF_BLOCKEDUSERS_USER)
query.whereKey(PF_BLOCKEDUSERS_USER, equalTo: usr)
//THIS WORKS BUT IS ASYNCHRONOUS AND I WANT IT TO BE SYNCHRONOUS
// query.countObjectsInBackgroundWithBlock {
// (count: Int32, error: NSError?) -> Void in
// if error == nil {
// print("Sean has played \(count) games")
// violations = count
// }
// }
//WANT TO MAKE IT SYNCHRONOUS -- THIS DOES NOT WORK
violations = query.countObjects(<#T##error: NSErrorPointer##NSErrorPointer#>)
return violations
}
How to use query.countObjects(...)
correctly here?
Here is the syntax for passing an NSError
in countObjects
along with code for printing the error should you receive one:
var error: NSError?
violations = query.countObjects(&error)
if error != nil {
print(error?.localizedDescription)
}
Here is a little explanation to help you further understand that error type.
The NSErrorPointer
type is essentially the same as NSError**
in Objective-C and indicates that the address of an object, where it actually lives and not just the object’s pointer, is needed to fulfill the argument type. This is a common error-handling pattern in Objective-C.
The &
operator allows you to pass such an address to a function. The argument that is passed in can than be modified instead of being limited to only the scope of the function. This is known as an in-out parameter in Swift terminology because what goes in also goes out.