iphone为什么他要使用valueForKeyPath
我在internet上发现了一些类似以下内容的mapkit代码:iphone为什么他要使用valueForKeyPath,iphone,objective-c,Iphone,Objective C,我在internet上发现了一些类似以下内容的mapkit代码: - (void)recenterMap { NSArray *coordinates = [self.mapView valueForKeyPath:@"annotations.coordinate"]; CLLocationCoordinate2D maxCoord = {-90.0f, -180.0f}; CLLocationCoordinate2D minCoord = {90.0f, 180.0f}; f
- (void)recenterMap {
NSArray *coordinates = [self.mapView valueForKeyPath:@"annotations.coordinate"];
CLLocationCoordinate2D maxCoord = {-90.0f, -180.0f};
CLLocationCoordinate2D minCoord = {90.0f, 180.0f};
for(NSValue *value in coordinates) {
CLLocationCoordinate2D coord = {0.0f, 0.0f};
[value getValue:&coord];
if(coord.longitude > maxCoord.longitude) {
maxCoord.longitude = coord.longitude;
}
--omitted the rest
我想知道为什么valueForKeypath用于获取坐标数据,而不仅仅是
[self.mapView.annotations]
这与速度有关吗?他使用
valueForKeyPath:
构造返回所有注释的所有坐标数组
假设self.mapView
是MKMapView
,那么它有一个annotations
属性,该属性返回符合MKAnnotation
协议的对象数组。这意味着该数组中的每个对象都应该实现坐标
属性。通过调用[self.mapView valueForKeyPath:@“annotations.coordinate”]
他可以立即获得所有坐标的数组,而无需迭代数组中的每个注释项
如果不在这里使用KVC构造,他必须执行类似的操作:
NSMutableArray *coordinates = [NSMutableArray array];
for (id<MKAnnotation> annotation in self.mapView.annotations)
[coordinates addObject:annotation.coordinate];
NSMutableArray*坐标=[NSMutableArray];
for(self.mapView.annotations中的id注释)
[coordinates addObject:annotation.coordinate];
总之,它只会使代码更简单、更易于阅读。是的。你说得对。我总是忘记在NSArray上的行为,因为我积极地避免它。