I have made a query in parse and fetched an array of GeoPoint coordinates. This was done inside a closure. I can only access the array values inside that closure. I need to be able to use those value so they can be used as annotations on a map but I can't get to them. Can somebody tell me how to get the array values out of the closure.
code:
var user = PFUser.currentUser()
user["location"] = geopoint
var query = PFUser.query()
query.whereKey("location", nearGeoPoint:geopoint)
query.limit = 10
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]!, error: NSError!) -> Void in
for object in objects {
var user:PFUser = object as PFUser
var otherUsersCoord = [PFGeoPoint]()
otherUsersCoord.append(user["location"] as PFGeoPoint)
println("The other users coords are: \(otherUsersCoord)")
}
})}
Declare
otherUsersCoord
as a var outside the closure expression, rather than inside it. When it is assigned to within the closure, that change will be reflected in the variable outside the closure. This is known as “capturing”otherUsersCoord
. Capturing external context is what makes closures more than just functions.Beware though, you still need to wait for the closure to actually run before the variable will have the value you decide. It won’t be instantly synchronously available. Also, capturing external variables keeps them alive and can occasionally result in cyclic references and similar problems (this is why sometimes when you refer to a member variable or function you get a warning about “capturing self”).
You would usually do something like:
If the closure is in a method on some helper class, pass it a completion block parameter that takes the array as a parameter. When the completion block is called, store the array as an instance variable (and trigger an update to your UI) or create the annotations and set them onto your map view (which would be an instance variable).
If the closure is in a method on your class that owns the map view then you can skip the completion block part and just deal with the array directly to update your instance variable / map.