1

I'm in a situation where in the

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

method, I need to dynamically change the implementation of the subtitle method for the annotation object. The reason I need to do this is because I'm doing some computations based on latitudes and longitudes that are changing frequently (which I wish to display as the subtitle) ...so when I first create the id object, it doesn't make sense to do that computation at that time.

How would I dynamically override the subtitle method for my custom id object? Can someone point me in the direction of doing that? Or are there any other approaches I could take?

EDIT: To be a bit more clear... I want to add the annotation custom object to the map BEFORE figuring out what the title and subtitle should be for that annotation object. I want to wait until the user touches on the annotation on the map..and when it shows the popup, that's where I want to calculate what to show as the subtitle. That's why I thought of dynamically overriding the subtitle method of the custom id object.

Thanks!

4

1 回答 1

2

If you need to dynamically change the implementation of a method at run time, that might call for an application of strategy pattern.

With C blocks, we can do it in a flexible and quick way. Have your custom annotation delegate its implementation of subtitle to the return value of a block property. Then, in your map view's delegate, define blocks that calculate the subtitle based on your requirements, and assign them to the annotation's property.

Sketch of a custom annotation implementation that delegates its subtitle implementation:

typedef NSString* (^AnnotationImplementationSubtitleBlock)();

@interface AnnotationImplementation : NSObject <MKAnnotation>

@property (nonatomic, copy) AnnotationImplementationSubtitleBlock *subtitleBlock;

@end

@implementation AnnotationImplementation

- (NSString *)subtitle
{
    return self.subtitleBlock();
}

// Rest of MKAnnotation methods

@end

Also a sketch of the implementation of the map view delegate method where the blocks are created and assigned:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    AnnotationImplementation *customAnnotation = (AnnotationImplementation *)annotation;
    if (/* some condition causing you to do it one way */) {
        customAnnotation.subtitleBlock = ^{
            //calculate the subtitle some way 
            return calculatedSubtitle;
        }
    }
    else if (/* some condition causing you to do it another way */) {
        customAnnotation.subtitleBlock = ^{
            //calculate the subtitle the other way
            return calculatedSubtitle;
        }      
    }
    ... rest of method
}
于 2013-03-30T08:25:27.763 回答