Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iphone为什么他要使用valueForKeyPath_Iphone_Objective C - Fatal编程技术网

iphone为什么他要使用valueForKeyPath

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

我在internet上发现了一些类似以下内容的mapkit代码:

- (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上的行为,因为我积极地避免它。