2010-04-30 63 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]]; 
    } 
}