Search code examples
iosswiftparse-platformpfquery

how to keep retrieved data from parse.com, but outside of findObjectsInBackgroundWithBlock{}?


I have a question about PFQuery with parse iOS SDK.

I have a several geoPoints data in parse with className SpotList. Inside of it, there is two column, i.e. SpotName and SpotLocation.

After retrieve the data, I tried to print it with println(self.SpotNames) it in four different locations (see comment in code below).

My question is, why I got an empty array [] if I do println in location 4? Meanwhile, I can get the whole data by doing println in location 1, 2, and 3. Also, is there any method to get the whole data in location 4?

thank you for your help!

var SpotNames              = [String]()
var SpotGeoPoints          = [PFGeoPoint]()
var SpotLocationLatitudes  = [CLLocationDegrees]()
var SpotLocationLongitudes = [CLLocationDegrees]()
var SpotLocations          = [CLLocationCoordinate2D]()

override func viewDidLoad() {
    super.viewDidLoad()

    var query:PFQuery = PFQuery(className: "SpotList")
    query.orderByAscending("SpotName")
    query.findObjectsInBackgroundWithBlock{ (objects:[AnyObject]! , error:NSError!)-> Void in
        if !(error != nil){
            for object in objects!   {
                self.SpotNames.append(object["SpotName"] as String)
                self.SpotGeoPoints.append(object["SpotLocation"] as PFGeoPoint)
                self.SpotLocationLatitudes.append(self.SpotGeoPoints.last?.latitude as CLLocationDegrees!)
                self.SpotLocationLongitudes.append(self.SpotGeoPoints.last?.longitude as CLLocationDegrees!)
                // location 1
            }
            // location 2
        }
        // location 3
    }
    // location 4
}

Solution

  • Since findObjectsInBackgroundWithBlock is an asynchronous method, it returns immediately. So, when you reach location 4, you probably will get an empty array. If you really want to get the result right there, use synchronous version findObjects, but doing a heavy work on main thread is always not a good idea.