我有一个NSMutableArray,我需要向已调度的多个块中添加对象。这是确保阵列安全更改的可接受方法吗?这些已经从内部和NSOperation分发并在后台运行。我正在从该线程内串行加载数据,但是一次加载位置列表的速度非常慢。
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);
for (NSDictionary *theLocation in self.weatherLocations) {
// Add a task to the group
dispatch_group_async(group, queue, ^{
NSLog(@"dispatching...");
int i = 0;
WeatherObject *weatherObject = [forecastDownloader getForecast:[theLocation objectForKey:@"lat"] lng:[theLocation objectForKey:@"lng"] weatherID:[[theLocation objectForKey:@"id"] intValue]];
}
if(!weatherObject){
//need to implement delegate method to show problem updating weather
NSLog(@"problem updating weather data");
}else{
NSLog(@"got weather for location...");
dispatch_sync(serialQueue, ^{
[weatherObjects addObject:weatherObject];
});
}
});
}
// wait on the group to block the current thread.
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"finished getting weather for all locations...");
//we will now do something with the weatherObjects
那是行不通的,因为您每次都在制作一个新的锁,而不是对变量使用单个锁(类比:想像一扇锁着的房间门。如果每个人都有自己的带锁门,那就没关系了他们将其锁定,因为其他所有人都会进入他们自己的门)。
您可以对所有迭代使用单个NSLock,也可以(基本上等效地)使用单个串行调度队列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句