cocoa - How do you safely lock a variable using GCD? -


i have nsmutablearray need add objects multiple blocks have dispatched. acceptable way make sure array safely being changed? these being dispatched inside , nsoperation , running in background. loading data within thread serially getting slow load list of locations @ once.

nsmutablearray *weatherobjects = [[nsmutablearray alloc] init]; forecastdownloader *forecastdownloader = [[forecastdownloader alloc] init];  dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0); dispatch_group_t group = dispatch_group_create();  dispatch_queue_t serialqueue; serialqueue = dispatch_queue_create("us.mattshepherd.forecasterserialqueue", null);  (nsdictionary *thelocation in self.weatherlocations) {      // add task group     dispatch_group_async(group, queue, ^{         nslog(@"dispatching...");         int = 0;         weatherobject *weatherobject = [forecastdownloader getforecast:[thelocation objectforkey:@"lat"] lng:[thelocation objectforkey:@"lng"] weatherid:[[thelocation objectforkey:@"id"] intvalue]];          }         if(!weatherobject){             //need implement delegate method show problem updating weather             nslog(@"problem updating weather data");         }else{             nslog(@"got weather location...");             dispatch_sync(serialqueue, ^{                 [weatherobjects addobject:weatherobject];             });           }     });  } // wait on group block current thread. dispatch_group_wait(group, dispatch_time_forever);  nslog(@"finished getting weather locations..."); //we weatherobjects 

that's not going work because you're making new lock each time, rather using single lock variable (analogy: imagine locked door room. if gets own door lock, hardly matters lock it, since else come in own door).

you can either use single nslock iterations, or (basically equivalently) single serial dispatch queue.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -