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

How to override a readonly property in a subclass of CLLocation?

我正在子类化 CLLocation 以添加 属性:

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

@interface MyLocation : CLLocation

@property (nonatomic, copy) NSString *name;

@end

问题是我需要能够更新 MyLocationcoordinate 属性,它在超类中声明为 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:]: 无法识别的选择器发送到实例 意味着我所做的没有随心所欲地工作。我猜CLLocation.m中的coordinate没有setter?

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

在这种情况下,您应该只复制 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 
}