views:

198

answers:

1

Hi,

I found some mapkit code on the internet that looks like this:

- (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

I want to know why valueForKeypath is used to get the coordinate data, instead of just

[self.mapView.annotations]

Has it something to do with speed?

+2  A: 

He's using the valueForKeyPath: construct to return an array of all the coordinates for all of the annotations.

Assuming that self.mapView is an MKMapView then it has an annotations property which returns an array of objects conforming to the MKAnnotation protocol. That means that every object in that array should implement the coordinate property. By issuing a call to [self.mapView valueForKeyPath:@"annotations.coordinate"] he is immediately getting an array of all of the coordinates without having to iterate over each individual annotation item in the array.

Without using the KVC construct here he'd have to do something similar to this:

NSMutableArray *coordinates = [NSMutableArray array];
for (id<MKAnnotation> annotation in self.mapView.annotations)
    [coordinates addObject:annotation.coordinate];

In all, it just makes for simpler, easier to read code.

Ashley Clark
Yup. You're right. I always forget about that behavior on NSArray because I actively avoid it.
bbum