NSManagedObject子类符合<mkannotation>协议?</mkannotation>

时间:2010-07-20 02:59:00

标签: iphone core-data mkannotation

我的主要问题是存储Core Data不支持的数据。我已经将CLLocation属性存储为可转换属性。我认为正确的方法是声明一个瞬态坐标属性。但是我不断收到EXC_BAD_ACCESS错误。

编辑:

我当前的子类具有以下界面:

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface Event : NSManagedObject {

}

@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSDate* timeStamp;
@property (nonatomic, retain) CLLocation *location;

@end

所以我需要添加

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate;

符合协议。 (setCoordinate是可选的,但如果我想让注释可拖动,我需要它)

在核心数据中,location属性是可转换的。我在实现中使用@dynamic来生成访问器。我在整个代码中都使用了这个属性,所以我不想保留它。

我认为最好的解决方法是将核心数据中的坐标属性定义为瞬态,但我并没有对实现做错。

- (CLLocationCoordinate2D)coordinate {
    CLLocationCoordinate2D cor = CLLocationCoordinate2DMake(self.location.coordinate.latitude,
    self.location.coordinate.longitude);
    return cor;
}

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate {
    CLLocation *newLoc = [[CLLocation alloc] initWithLatitude:newCoordinate.latitude
    longitude:newCoordinate.longitude];
    [self.location release];
    self.location = newLoc;
} 

我尝试了几种方法,但这是最新的方法。

编辑2: EXC_BAD_ACCESS位于:

_kvcPropertysPrimitiveSetters

2 个答案:

答案 0 :(得分:3)

只要协议不以某种方式覆盖上下文对实例的管理,您就可以使NSManagedObject子类符合您希望的任何协议。 MKAnnotation协议应该是完全安全的。

更新

你的问题很可能在这里:

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate {
    CLLocation *newLoc = [[CLLocation alloc] initWithLatitude:newCoordinate.latitude
                                                    longitude:newCoordinate.longitude];
    [self.location release]; //<-- Don't release properties!
    self.location = newLoc;
}

生成器访问器将为您处理保留。当你直接释放它们时,你就搞砸了管理层。你也在泄漏newLoc。尝试:

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate {
    CLLocation *newLoc = [[CLLocation alloc] initWithLatitude:newCoordinate.latitude
                                                    longitude:newCoordinate.longitude];
    self.location = newLoc;
    [newLoc release];
}

答案 1 :(得分:1)

知道你在哪里得到EXC_BAD_ACCESS错误会很好,但是这里有几个想法。首先,假设有一个想要呼叫setCoordinate:的外部课程,你应该真正将@property更改为列出coordinatereadwrite,因为你正在抚摸世界不允许改变这个值。您可以尝试的另一件事是继续并在coordinate中实际发送setCoordinate:,然后您可以取消自定义coordinate方法,并允许Core Data为您写一个更快的方法。