multithreading - Main thread doesn't wait background thread to finish in Swift -


here's problem : i'm doing background work, parse json , write objects realm, , in main thread try update ui (reloading tableview, it's linked array of object). when reload ui, tableview doesn't update, realm wasn't updated. have reload view see updates. here's code :

    if (realm().objects(objects).filter("...").count > 0)     {         var results = realm().objects(objects) // existing objects it's empty         tableview.reloaddata()     }     request(.get, url).responsejson() {     (request, response, data, error) in     let priority = dispatch_queue_priority_default         dispatch_async(dispatch_get_global_queue(priority, 0)) {             // parsing json             realm().write {                 realm().add(object)             }             dispatch_sync(dispatch_get_main_queue()) {                 // updating ui                 if (realm().objects(objects).filter("...").count > 0)                 {                     results = realm().objects(objects) // existing objects it's empty                     tableview.reloaddata()                 }             }         }     } 

i have bad threads, couldn't find what. can know what's wrong?

thank answer!

such workflow makes more sense me case:

let priority = dispatch_queue_priority_default dispatch_async(dispatch_get_global_queue(priority, 0)) {     // parsing json     realm().write {         realm().add(object)         dispatch_sync(dispatch_get_main_queue()) {             // updating ui             if (realm().objects(objects).filter("...").count > 0)             {                 results = realm().objects(objects) // existing objects it's empty                 tableview.reloaddata()             }         }     }     } 

note: have problem timing in original workflow: ui might updated before write's block executed, why ui looks abandoned; idea above more synchronised way between tasks, according performance's schedule.


Comments