Getting Data from Findobjectsinbackgroundwithblock in Swift

Getting data from findObjectsInBackgroundWithBlock in swift

You'll need to cast your [AnyObject] to a [PFObject] and then you can use the standard Parse methods to get the data out.

if let staffObjects = objects as? [PFObject] {
for staff in staffObjects {
// Use staff as a standard PFObject now. e.g.
let firstName = staff.objectForKey("first_name")
}
}

findObjectsInBackgroundWithBlock: gets data from Parse, but data only exists inside the block

The last NSLog(@"The dictionary is %@", self.scoreDictionary) statement does not actually execute after the block completes. It executes after the findObjectsInBackgroundWithBlock method returns. findObjectsInBackgroundWithBlock presumably runs something in a separate thread, and your block may not actually execute at all until some length of time after that last NSLog statement. Graphically, something like this is probably happening:

Thread 1 
--------
retriveDataFromParse called
invoke findObjectsInBackgroundWithBlock
findObjectsInBackgroundWithBlock queues up work on another thread
findObjectsInBackgroundWithBlock returns immediately |
NSLog statement - self.scoreDictionary not yet updated |
retriveDataFromParse returns |
. V
. Thread 2, starting X milliseconds later
. --------
. findObjectsInBackgroundWithBlock does some work
. your block is called
. for-loop in your block
. Now self.scoreDictionary has some data
. NSLog statement inside your block

You probably want to think about, what do you want to do with your scoreDictionary data after you have retrieved it? For example, do you want to update the UI, call some other method, etc.? You will want to do this inside your block, at which point you know the data has been successfully retrieved. For example, if you had a table view you wanted to reload, you could do this:

for (PFObject *object in objects){
....
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUserInterfaceOrSomething];
});

Note the dispatch_async - if the work you need to do after updating your data involves changing the UI, you'll want that to run on the main thread.

How can I retrieve data from Parse, using getObjectInBackgroundWithId and saveInBackgroundWithBlock

This should work.

query.getObjectInBackgroundWithId("2Zn8ZfFKsA") {
(score: PFObject?, error: NSError?) -> Void in
if error == nil && score != nil {
println(score)
} else {
println("error")
}
}

Error with Parse Query findObjectsInBackgroundWithBlock

Try changing [AnyObject]? to [PFObject]?. This seems to be required by Swift 2.0.

So instead of:

findTimelineData.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in

Use:

findTimelineData.findObjectsInBackgroundWithBlock {
(objects:[PFObject]?, error:NSError?) -> Void in

You'll also need to change your iteration over the array objects, since they will now already be PFObject.



Related Topics



Leave a reply



Submit