OGeek|极客世界-中国程序员成长平台

标题: ios - 检查 MKPolyline 覆盖是否已经存在 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:29
标题: ios - 检查 MKPolyline 覆盖是否已经存在

如何检查折线是否已添加到 map 中?

我已经尝试了以下代码,但它似乎不起作用

for (MKPolyline *feature1 in self.mapView.overlays) {

       NSLog(@"feature1.title: %@", feature1.title);
       NSLog(@"olu.title: %@", polu.title);

       if (![feature1.title isEqualToString:polu.title]) {
             NSLog(@"NOT");
             [self.mapView addOverlay:polu];
       }
       else {
             NSLog(@"Already added");
       }
      }
     }

我也试过这个:

if (![self.mapView.overlays containsObject:polu]) {
    NSLog(@"NOT");
   [self.mapView addOverlay:polu];
}



Best Answer-推荐答案


当前的 for 循环一旦发现 一个 其他标题不匹配的叠加层,就会假定叠加层存在或不存在。

但此时,for 循环可能尚未检查剩余的叠加层(其中一个可能是您正在寻找的叠加层)。

例如:


相反,您希望在找到匹配的标题时停止循环,并且如果循环结束时没有找到匹配项,then 添加叠加层。

例子:

BOOL poluExists = NO;

for (MKPolyline *feature1 in self.mapView.overlays) {

    NSLog(@"feature1.title: %@", feature1.title);
    NSLog(@"olu.title: %@", polu.title);

    //STOP looping if titles MATCH...
    if ([feature1.title isEqualToString:polu.title]) {
        poluExists = YES;
        break;
    }
}

//AFTER the loop, we know whether polu.title exists or not.
//If it existed, loop would have been stopped and we come here.
//If it didn't exist, loop would have checked all overlays and we come here.
if (poluExists) {
    NSLog(@"Already added");
}
else {
    NSLog(@"NOT");
    [self.mapView addOverlay:polu];
}


在问题的第二个示例中,containsObject: 仅在 polu 是第一次调用 addOverlay 时给出的原始对象时才有效,因为在这种情况下,containsObject: 将比较指针地址,而不是叠加层的 title 属性。

关于ios - 检查 MKPolyline 覆盖是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28947818/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4