2013-07-26 85 views
1

我在我的.xib文件中添加了一个按钮,我想用它来删除已添加的最后一个注释。如何删除地图上的最后一个注释查看

所以在触及动作我已经实现了这一点:

-(IBAction)DeleteAnnotation:(id)sender { 
    [mapview removeAnnotation:[mapview.annotations lastObject]]; 
} 

,我甚至已经尝试过这种方式:

-(IBAction)DeleteAnnotation:(id)sender { 
    [self.mapview removeAnnotation:self.mapview.annotations.lastObject]]; 
} 

其中mapview是我MKMapView出口。

我在这两种方式遇到的问题是,我必须在删除注释之前多次按下此特定按钮。

此外,注释以相当随机的方式移除自己。

有什么我做错了吗?还是它是一个软件和模拟器的问题?

回答

3

MKMapViewannotations属性不保证以与添加它们相同的顺序返回注释。

假定annotations数组属性将按照您添加的顺序返回注释,这很可能是您看到的“奇怪”行为的原因。请参阅这些相关解答了一些细节:


为了得到你想要的我以为是简单的行为(“删除被明确添加的最后一个注解由我的代码“),这里有三种可能的方法(可能有其他方法):

  1. 最简单的方法是在强大的财产中保留对最后添加的注释的引用(当您致电addAnnotation时更新引用)。当你想删除“最后添加的注释”时,将保存的参考传递给removeAnnotation。例如:

    //in the interface... 
    @property (nonatomic, strong) id<MKAnnotation> lastAnnotationAdded; 
    
    //in the implementation... 
    
    //when you add an annotation: 
    [mapview addAnnotation:someAnnotation]; 
    self.lastAnnotationAdded = someAnnotation; //save the reference 
    
    //when you want to remove the "last annotation added": 
    if (self.lastAnnotationAdded != nil) 
    { 
        [mapview removeAnnotation:self.lastAnnotationAdded]; 
        self.lastAnnotationAdded = nil; 
    } 
    
  2. 另一种选择是循环通过地图视图的annotations阵列和搜索“最后”注释(或任何属性你感兴趣)。一旦你参考了“最后一个”(可能不一定是阵列中的最后一个对象),你可以拨打removeAnnotation。这种方法假定您在注释对象本身中有一些属性,可以让您将注释标识为“最后一个”注释。这可能并不总是可能的。

  3. 另一种选择是保留自己的注释数组,并在每次调用addAnnotation时向此数组添加注释对象。这与将单个引用保留为“最后添加的注释”类似,除非您按照您可以依赖的顺序跟踪整个列表。要删除“最后一个”,您将从数组中获取lastObject而不是地图视图(假设您保持该数组的顺序)。在添加/删除地图注释时,您必须确保您的阵列保持同步。