删除注释数组中的重复项

时间:2013-09-18 01:32:57

标签: ios objective-c annotations mkmapview

我有一个MKMapKit我正在使用我从API中获取的数据填充注释。每个注释都有标题,描述,URL和坐标。我有一个按钮,我添加到导航栏以获取更多结果并填充更多注释。问题是当API运行时,新的结果会填充地图,其中包含已经提取的注释的副本。我正在尝试使用if语句从数组中删除重复的注释,但它不起作用。有什么建议?提前致谢。

-(void)layAnnotations
{

if (self.annotations) {
    [self.mapView removeAnnotations:self.annotations];
}

self.annotations = [NSMutableArray array];

for (Object *aObject in self.objectArray) {
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [aObject.latitude floatValue];
    coordinate.longitude = [aObject.longitude floatValue];

    Annotations *annotation = [[Annotations alloc] init];



    annotation.title = aObject.objectTitle;
    annotation.subtitle = aObject.description;
    annotation.url = aObject.url;
    annotation.coordinate = coordinate;

    //attempting to filter duplicates here
    if (![self.annotations containsObject:annotation]) {
        [self.annotations addObject:annotation];
    }        

    annotation = nil;

}

[self mutateCoordinatesOfClashingAnnotations:self.annotations];

[self.mapView addAnnotations:self.annotations];

}

2 个答案:

答案 0 :(得分:1)

因为你init为每个对象添加了一个新的注释,所以它们永远不会是同一个引用,而是containsObject中的比较。相反,你可以循环遍历所有注释,并检查新注释是否与现有注释匹配,副标题,网址和坐标(或者你知道哪些是唯一的)。

如果您想要更多参与,可以覆盖isEquals函数,以便进行比较。此示例显示了如何开始。我们的想法是编写他们的isEqualToWidget函数版本来比较每个注释的属性值。我认为这是更好的解决方案。

Best practices for overriding isEqual: and hash

答案 1 :(得分:1)

让我们说URL是你的注释的唯一标识符,那么它应该是:

NSMutableArray *annotations = [NSMutableArray array];

for (Object *aObject in self.objectArray) {
    if (![[self.annotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"url == %@", aObject.url] count]) {
/* you also can construct your predicate like [NSPredicate predicateWithFormat:@"((title == %@) AND (coordinate.latitude == %f) AND (coordinate.longitude == %f) AND (subtitle == %@))", aObject.title, aObject.latitude.floatValue, aObject.longitude.floatValue, aObject.subtitle]; */
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = [aObject.latitude floatValue];
        coordinate.longitude = [aObject.longitude floatValue];

        Annotations *annotation = [[Annotations alloc] init];
        annotation.title = aObject.objectTitle;
        annotation.subtitle = aObject.description;
        annotation.url = aObject.url;
        annotation.coordinate = coordinate;
        [self.annotations addObject:annotation];
    }
}
在这种情况下,

containsObject实际上永远不会返回YES,因为每次都会创建一个新对象,但不会使用注释数组中的相同对象

不要忘记确保您实际执行NSMutableArray *annotations = [NSMutableArray array];,否则您将始终从filteredArrayWithPredicate:方法获得空数组。