如何覆盖CLLocation的子类中的只读属性?

时间:2017-03-22 14:12:59

标签: objective-c properties cllocation subclassing

我正在为CLLocation创建子类以添加属性:

#import <UIKit/UIKit.h>
@import CoreLocation;

@interface MyLocation : CLLocation

@property (nonatomic, copy) NSString *name;

@end

问题是我需要能够更新MyLocation的{​​{1}}属性,该属性在超类中声明为coordinate

readonly

在此处提供了类似的答案,我创建了一个私人扩展程序,我将// CLLocation.h @property(readonly, nonatomic) CLLocationCoordinate2D coordinate; 重新声明为coordinate

readwrite

由于编译器抱怨这一点,我还添加了@interface MyLocation () @property(nonatomic, assign, readwrite) CLLocationCoordinate2D coordinate; @end 关键字:

@dynamic

然后我创建了一个方法来用另一个坐标更新我的子类的实例:

@implementation MyLocation

@dynamic coordinate;

@end

问题是,当我致电@implementation MyLocation @dynamic coordinate; -(void)updateCoordinate:(CLLocationCoordinate2D)newCoordinate { self.coordinate = newCoordinate; } @end 时,我收到了 -updateCoordinate消息的崩溃:无法识别的选择器已发送到实例,这意味着我所做的并不起作用我一跳。我想-[MyLocation setCoordinate:]中的coordinate没有设置器?

有人能解释一下这里发生了什么并提出任何解决方案吗?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您应该只复制CLLocation。它有一个不可改变的原因。例如:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)new
           fromLocation:(CLLocation *)old{


    new = [[[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(old.coordinate.latitude, -1.000028276362)
                                             altitude:old.altitude
                                   horizontalAccuracy:old.horizontalAccuracy
                                     verticalAccuracy:old.verticalAccuracy
                                            timestamp:old.timestamp] autorelease];

    return new 
}