2010-04-30 68 views
1

我有這段代碼在我的mkmapview中刪除一個註釋(引腳)而不擦除我的藍點(userLocation)。問題是,它刪除了我添加的看似隨機數的引腳。當它通過IBAction被調用時,它將刪除前5個,然後再次單擊它將刪除下3個,然後是下2個,然後是最後一個。刪除Annotation一次刪除隨機數量的註釋

當我按下時,我需要它來刪除最新的引腳等。等等

for (int i = 0; 
    i < [mapView.annotations count]; 
    i++ 

    ) 



{ if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyAnnotation class]]) 
    { 
[mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; 
    } 
} 

回答

1

問題是,你正在修改annotation集合,同時迭代它。在循環的每次執行中,循環的終止條件[mapView.annotations count]都會更改其值。這將導致無法預料的行爲。你應該

  • 要麼把要刪除進入環內的空可變數組然後調用removeAnnotations:這個數組作爲參數,則退出循環後,所有註釋,
  • 或計數從註釋最高指數爲0。
+0

繼奧萊Begermann的建議,這項工作\t for(int i = [mapView.annotations count] -1; i> = 0; i--) \t { \t \t [mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; \t} – 2010-08-26 17:05:12

0

使用此代碼

NSInteger *counter = [mapView.annotations count]; 
for (int i = 0; i < counter; i++) 
{ 

    if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyAnnotation class]]) 
    { 
     [mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; 
    } 
}