关于cocoa-touch:实时设置MKA注释坐标

Setting MKAnnotation coordinates in real time

我有一个符合MKAnnotation协议的Map Point对象。它会按预期工作,直到我尝试实时更改其坐标为止。

一开始我尝试使用:

1
[map_point setCoordinate : new_coordinate];

它不起作用,因为该属性为"只读"。 Apple文档说我应该添加一个自定义" setCoordinate ",并且它必须符合KVO。

已阅读有关KVO的文档。希望有人能给出一个基本示例,说明如何使setCoordinate KVO兼容。


仅以完全相同的格式实现setCoordinate:方法将自动符合KVO / KVC。您不需要执行任何其他操作:

1
2
3
4
5
6
- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate
{
    //In this example, the ivar in this class that holds the coordinate
    //is named"coord".  Simply assign the new value to it...
    coord = newCoordinate;
}

使用完全一样的方法命名(尽管您可以更改参数名称newCoordinate),KVO通知将自动为您发出。

请参阅是否需要调用willChangeValueForKey:和didChangeValueForKey :?有关详细信息。

但是,如果需要以不兼容的方式更改coordinate,则可以手动生成KVO通知:

1
2
3
4
5
6
- (void)someNonCompliantMethod
{
    [self willChangeValueForKey:@"coordinate"];
    coord = someNewCoordinate;
    [self didChangeValueForKey:@"coordinate"];
}

请注意,只需将coordinate属性声明为assignreadwrite而不是readonly

,就可以完全避免手动实现setCoordiante:方法(和ivar)。

1
2
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
//and @synthesize in the @implementation

现在,您无需编写自定义的getter或setter,就可以从实例化此类的代码中直接将其分配给coordinate

1
[map_point setCoordinate : new_coordinate];

或:

1
map_point.coordinate = new_coordinate;

最后,如果注释所需的唯一属性是titlesubtitlecoordinate,则还可以完全避免创建自定义类,而使用内置的MKPointAnnotation类来实现可写coordinate属性。