ios - Capturing closure values in Swift -
my question similar several others here can't work. i'm making api call via helper class wrote.
first tried standard function return value , result expected. background task completed after tired assign result.
now i'm using closure , can value view controller still stuck in closure, have same problem. know need use gcd assignment happen in main queue.
this have in view controller
var artists = [string]() let api = apicontroller() api.getartistlist("foo fighters") { (thelist) -> void in if let names = thelist { dispatch_async(dispatch_get_main_queue()) { artists = names print("in closure: \(artists)") } } } print ("method 1 results: \(artists)")
as results are:
method 1 results: [] in closure: [foo fighters & brian may, uk foo fighters, john fogerty foo fighters, foo fighters, foo fighters feat. norah jones, foo fighters feat. brian may, foo fighters vs. beastie boys]
i know why happening, don't know how fix :( api calls need async, best practice capturing these results? based on user selects in table view i'll making subsequent api calls not can handle inside closure
the easy solution whatever you're doing @ print()
, inside closure.
since you're dispatch_async
ing main queue (the main/gui thread), can complete processing there. push new view controller, present modal data, update current view controller, etc.
just make sure don't have multiple threads modifying/accessing local/cached data being displayed. if it's being used uitableviewdelegate
/ uitableviewdatasource
implementations, throw fits if start getting wishy-washy or inconsistent return values.
as long can retrieve data in background, , processing needs occur on main thread instance variable reassignment, or kind of array appending, do that on main thread, using data retrieved on end. it's not heavy. if is heavy, you're going need more sophisticated synchronization methods protect data.
normally pattern looks like:
dispatch_async(getbackgroundqueue(), { var thedata = getthedatafromnetwork(); dispatch_async(dispatch_get_main_queue() { self.data = thedata // update instance variable of viewcontroller self.tableview.reloaddata() // or other 'reload' method }); })
so you'd refresh table view or notify viewcontroller operation has completed (or local data has been updated), should continue main-thread processing.
Comments
Post a Comment