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?
He’s using the
valueForKeyPath:construct to return an array of all the coordinates for all of the annotations.Assuming that
self.mapViewis anMKMapViewthen it has anannotationsproperty which returns an array of objects conforming to theMKAnnotationprotocol. That means that every object in that array should implement thecoordinateproperty. 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:
In all, it just makes for simpler, easier to read code.