我的主要问题是存储 Core Data 不支持的数据。我已经有一个 CLLocation 属性存储为可转换属性。我认为正确的方法是声明一个 transient 坐标属性。但是,我不断收到 EXC_BAD_ACCESS 错误。
编辑:
我当前的子类具有以下接口(interface):
#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;
遵守协议(protocol)。 (setCoordinate 是可选的,但如果我想让注释可拖动,我需要它)
在核心数据中,位置属性是可转换的。我在实现中使用 @dynamic 来生成访问器。我在整个代码中使用这个属性,所以我不想保留它。
我认为最好的方法是将核心数据中的坐标属性定义为 transient ,但我在实现方面并不是绝对错误的。
- (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
最佳答案
您可以使 NSManagedObject 子类符合您希望的任何协议(protocol),只要该协议(protocol)不会以某种方式覆盖实例的上下文管理。 MKAnnotation 协议(protocol)应该是完全安全的。
更新:
您的问题很可能在这里:
- (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];
}
关于iphone - NSManagedObject 子类符合 <MKAnnotation> 协议(protocol)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3286700/