I have a background task (usingParse.com API) that fetches and calculates the data for a tableview:
var usedMessages = [String]()
var currentMessages = [Message]()
func getCurrentMessages() {
if currentUser != nil {
var entryQuery = Entry.query()
entryQuery.whereKey("user", equalTo: currentUser)
entryQuery.whereKey("originatedFromType", equalTo: "message")
entryQuery.findObjectsInBackgroundWithBlock { (entryObjects: [AnyObject]!, getEntriesError: NSError!) -> Void in
for object in entryObjects {
var entry = object as Entry
usedMessages.append(entry.originatedFromId)
}
var messageQuery = Message.query()
messageQuery.whereKey("endDate", greaterThan:NSDate())
messageQuery.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
for object in objects {
var message = object as Message
if !contains(usedMessages, message.objectId) {
currentMessages.append(message)
}
}
self.tableview.reloadData()
}
}
}
}
Is this the correct way to handle fetching data for a tableview and then reloading the tableviews data? Or should I use a delegate that notifies the tableview that data has changed? or maybe even query.findObjectInBackgroundWithTarget and send the results?
You should always make sure that the reloadData and any UI updates happen in the main thread. Also check if the method does not return an error.
messageQuery.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if (error == nil)
{
//Your code.
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
self.tableView.reloadData()
})
}
else
{
// Log the error
}
}