iOS动态覆盖id <mkannotation> subclass </mkannotation>中的字幕方法

时间:2013-03-30 07:29:42

标签: iphone ios override mapkit subclass

我处于

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

方法,我需要动态更改注释对象的字幕方法的实现。我需要这样做的原因是因为我正在做一些基于经常变化的纬度和经度的计算(我希望显示为副标题)...所以当我第一次创建id对象时,它不会那时做那个计算是有意义的。

如何动态覆盖自定义ID对象的字幕方法?有人能指出我这样做的方向吗?或者我可以采取其他方法吗?

编辑: 为了更清楚一点......我想在确定该注释对象的标题和副标题之前,将注释自定义对象添加到地图中。我想等到用户触摸地图上的注释...当它显示弹出窗口时,我想要计算显示为副标题的内容。这就是为什么我想到动态覆盖自定义id对象的字幕方法。

谢谢!

1 个答案:

答案 0 :(得分:2)

如果您需要在运行时动态更改方法的实现,则可能需要strategy pattern的应用程序。

使用C块,我们可以灵活快捷地完成。让自定义注释将其subtitle的实现委托给块属性的返回值。然后,在地图视图的委托中,定义根据您的要求计算字幕的块,并将它们分配给注释的属性。

委托其subtitle实现的自定义注释实现的草图:

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

也是创建和分配块的地图视图委托方法的实现草图:

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