gpt4 book ai didi

ios - 从可变数组中移除 MKPointAnnotation 对象

转载 作者:行者123 更新时间:2023-11-29 12:01:11 25 4
gpt4 key购买 nike

我有一个 map 应用程序,允许用户将注释保存为可变数组的收藏夹。然后可以在用户选择时显示所有喜欢的注释。

添加到可变数组的注释属于 MKPointAnnotation 类。我可以正确地向可变数组添加注释,但我还没有想出一个可以从可变数组中正确删除特定注释的工作解决方案。如何从包含多个保存为收藏夹的注释的可变数组中删除特定注释?在我的示例代码中发现了几个无效的解决方案。

//** Correctly adds a favorite annotation to the mutable array favoriteAnnotationsArray **
-(void)addToFavoriteAnnotationsArray{
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
NSArray *components = [favoritesString componentsSeparatedByString:@","];
annotation.coordinate = CLLocationCoordinate2DMake([components[1] doubleValue], [components[0] doubleValue]);
annotation.title = [components[2] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];

[self.favoriteAnnotationsArray addObject:annotation];

}
//** Need to remove a favorite annotation from the mutable array favoriteAnnotationsArray **
-(void)removeObjectFromFavoriteAnnotationsArray{

MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
NSArray *components = [favoritesString componentsSeparatedByString:@","];
annotation.coordinate = CLLocationCoordinate2DMake([components[1] doubleValue], [components[0] doubleValue]);
annotation.title = [components[2] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];

//** Used in first non-working solution below **
//NSMutableArray *objectToRemoveArray = [[NSMutableArray alloc] init];
//[objectToRemoveArray addObject:annotation];

//** The following three lines didn't remove any annotations from array **
//[self.favoriteAnnotationsArray removeObjectsInArray:objectToRemoveArray];
//[self.favoriteAnnotationsArray removeObject:annotation];
//[self.favoriteAnnotationsArray removeObjectIdenticalTo:annotation];

//** This only removes the last object in array and not necessarily the correct annotation to remove **
[self.favoriteAnnotationsArray removeLastObject];

}

最佳答案

您需要从 favoriteAnnotationsArray 中指定一个唯一的注释,以便成功删除它。

也许你可以试试下面的方法:

-(void)removeAnnotationFromFavoriteAnnotationsArrayWithTitle: (NSString *) titleString {
for(int i=0; i<self.favoriteAnnotationsArray.count; i++) {
MKPointAnnotation *annotation = (MKPointAnnotation *)[self.favoriteAnnotationsArray objectAtIndex:i];
NSString * annotationTitle = annotation.title;
if([annotationTitle isEqualToString:titleString]) {
[self.favoriteAnnotationsArray removeObject:annotation];
break;
}
}
}

如果标题的唯一性不足以让您区分注释,那么您可以考虑子类化 MKAnnotation 并添加一个唯一的属性并将其传递给上述函数而不是标题。

关于ios - 从可变数组中移除 MKPointAnnotation 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36959148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com