技巧說明:一個以上的線程同時操作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”