当前位置: 代码迷 >> Iphone >> iphone多线程操作NSArray时的一个技艺
  详细解决方案

iphone多线程操作NSArray时的一个技艺

热度:47   发布时间:2016-04-25 06:20:22.0
iphone多线程操作NSArray时的一个技巧
技巧说明:一个以上的线程同时操作NSArray, 任何一个有写操作,都容易引起“Collection was mutated while being enumerated” ”

所以在其中只有读操作的线程中,将此Array拷贝一份出来进行读取,可以解决此问题。


使用场景:移动地图时,地图上会及时出现当前窗口经纬度范围的物体(比如一些自己geo数据库中的优惠餐馆等)

程序结构:1. 在移动地图事件上触发网络请求。
                    2. 请求返回后,将返回的数据用MKAnnotion的方式显示在地图上

用户体验要求:在请求返回前,用户可以继续移动地图。这意味这1和2是异步的,需要在不同的线程中进行

主要代码:

线程1中,发出网络请求
- (void)mapView:(MKMapView *)map regionDidChangeAnimated:(BOOL)animated{	self.searchResult.location = [mapView region];	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];	[self.searchResult loadData];}


线程2中渲染mapView
- (void)update {	NSArray *sitesResult = [NSArray arrayWithArray:self.searchResult.results];	if (sitesResult && [sitesResult count]>0) {		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];		for (GHSite *site in sitesResult) {			BOOL found = NO;			for (MKAnnotation *ann in [mapView annotations]) {				if ([[ann title] isEqualToString:site.title]) {					found =YES;				}			}			if(!found)		 				[mapView addAnnotation:site];		}		[sitesResult release];		[super viewDidLoad];	}}



注意,如果没有下面这句话,会发生异常:
"Collection was mutated while being enumerated”
	NSArray *sitesResult = [NSArray arrayWithArray:self.searchResult.results];
  相关解决方案