Reputation: 3958
I would like to get an object and print it. So I have created a function that will deal with getting the object and returning it back.
The problem is, the object is printed too early.
This is my function:
func getParseObject(){
println("i'm inside the function")
var query = PFQuery(className: "testClass")
query.getObjectInBackgroundWithId("OWXnWkL") {(tempObject: PFObject?, error: NSError?) -> Void in
if error == nil && tempObject != nil {
println("object retrieved with success")
} else {
//error
}
}
return object
}
and this is the call:
var data = getParseObject()
println("data is: \(data)")
And this is the output of the console:
i'm inside the function
data is:
object retrieved with success
What is the best solution to deal with this problem?
Many thanks!
Upvotes: 2
Views: 214
Reputation: 72
The code from the closure from the getObjectInBackgroundWithId method is asynchronous and takes more time to be completed. So the code that is written after the closure ends is going to run first.
func getParseObject(){
println("i'm inside the function")
var query = PFQuery(className: "testClass")
query.getObjectInBackgroundWithId("OWXnWkL") {(tempObject: PFObject?, error: NSError?) -> Void in
if error == nil && tempObject != nil {
println("object retrieved with success")
//THIS RUNS SECOND::::::::
} else {
//error
}
}
return object
}
var data = getParseObject()
println("data is: \(data)") //:::::THIS RUNS FIRST::::::
Upvotes: 2
Reputation: 14068
You need to return your object value within the callback of the asynchronous request like this:
func getParseObject(){
println("i'm inside the function")
var query = PFQuery(className: "testClass")
query.getObjectInBackgroundWithId("OWXnWkL") {(tempObject: PFObject?, error: NSError?) -> Void in
if error == nil && tempObject != nil {
println("object retrieved with success")
} else {
//error
}
return object // <-- Return your value here
} // <-- Asynchronous request ends here
}
Upvotes: 2
Reputation: 1429
your problem is you're doing an asynchronous request, the request is executed in the background. Therefore, you return the object before having recovered the data on the server.
If you want to display the value returned by the function of the need to synchronously:
func getParseObject() -> PFObject {
var object : PFObject?
let query = PFQuery(className: "testClass")
let result = query.getObjectWithId("OWXnWkL")
if result != nil {
object = result
}
return object!
}
else you must to work with handlers :
var query = PFQuery(className: "testClass")
query.getObjectInBackgroundWithId("OWXnWkL") {(tempObject: PFObject?, error: NSError?) -> Void in
if error == nil && tempObject != nil {
println("object retrieved with success")
// Do something with the object!
} else {
//error
}
I hope I have helped you
Ysee }
Upvotes: 3