break & continue

代码写久了,连最基本的语法都忘记了。

    for (id obj in self.mapView.annotations) {
        
        if ([obj class] == [MKUserLocation class]) {
            break;
        }
        [self.mapView removeAnnotation:obj];
    }

这是项目中的一段代码,目的是去除自己当前位置意外的annotationView,结果总是非自己所愿。因为是简单不过的代码,没有多想,加入log才发现,整个循环并不能总是执行完毕,大部分都会在中间的某个地方跳出循环。这才注意到break这个关键字,想起来是中断循环的,转而换了continue,效果就对了。

正确的:

    for (id obj in self.mapView.annotations) {
        
        if ([obj class] == [MKUserLocation class]) {
            continue;
        }
        [self.mapView removeAnnotation:obj];
    }

or

    for (id obj in self.mapView.annotations) {
        
        if ([obj class] != [MKUserLocation class]) {
            [self.mapView removeAnnotation:obj];
        }
    }
原文地址:https://www.cnblogs.com/ihojin/p/break-continue.html