Iphone why is it using valueForKeyPath

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 coordinate data instead of just

[self.mapView.annotations]

      

How does this relate to speed?

+2


source to share


1 answer


It uses a construct valueForKeyPath:

to return an array of all coordinates for all annotations.

Assuming it self.mapView

is MKMapView

, then it has a property annotations

that returns an array of objects conforming to the protocol MKAnnotation

. This means that every object in this array must implement a property coordinate

. By issuing a call [self.mapView valueForKeyPath:@"annotations.coordinate"]

, it immediately gets an array of all coordinates without having to iterate over every single annotation element in the array.

Without using the KVC construct, here it would have to do something similar to this:



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

      

Overall, it just makes the code simpler and easier to read.

+4


source







All Articles