objective c - How to synchronize two asynchronous delegate methods callbacks in iOS? -
i'm writing simple weather app try solidify understanding of protocols , delegates. i'm in following situation:
- i have 2 data sources weather data (just nsobjects @ time) , view controller want update once have received data both sources.
- the 2 data sources have protocols adhere in view controller. delegate methods called once have received data own web service. mean data source 1 gets data before data source 2, vice-versa, or @ same time (don't know 100% if possible)
- i want update view once have received data both sources.
what best way this? thinking of nesting delegate methods, data source 1 notify data source 2 when has data (through protocols), have data source 2 notify view controller update view when has data. don't think correct/best way things.
any ideas?
thanks
this sounds fit gcd dispatch groups.
first, create dispatch group dispatch_group_create
. use dispatch_group_enter
before start request each service. call dispatch_group_leave
when receive response each service. can specify when both requests complete dispatch_group_notify
.
the code might this:
dispatch_group_t weathergroup = dispatch_group_create(); dispatch_group_enter(weathergroup); [weatherservice1 requestwithcompletion:^(response *response){ // response dispatch_group_leave(weathergroup); }]; dispatch_group_enter(weathergroup); [weatherservice2 requestwithcompletion:^(response *response){ // response dispatch_group_leave(weathergroup); }]; dispatch_group_notify(weathergroup, dispatch_get_main_queue(),^{ // executed after both requests finished });
see docs more details: https://developer.apple.com/library/ios/documentation/performance/reference/gcd_libdispatch_ref/#//apple_ref/doc/uid/tp40008079-ch2-sw19
Comments
Post a Comment