How*_*ett 39 core-data nsmanagedobject ios
所以,我的情况是这样的:
我的iOS应用程序中有一个NSManagedObject子类,作为一个属性,我想存储MKPolygon对象的内容.我决定解决这个问题的方式(以及它是否有效可能是一个不同的问题)是将polygon属性声明为可转换对象,然后存储包含多边形点的NSArray(作为NSValue对象).
为此,我在模型对象上编写了几个便捷类方法:
+ (NSArray *)coordsArrayFromMKPolygon:(MKPolygon *)polygon pointCount:(int)count
{
CLLocationCoordinate2D *coords = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D) * count);
[polygon getCoordinates:coords range:NSMakeRange(0, count)];
NSMutableArray *coordsArray = [NSMutableArray array];
for (int i = 0; i < count; i++) {
NSValue *coordVal = [NSValue valueWithBytes:&coords[i] objCType:@encode(CLLocationCoordinate2D)];
[coordsArray addObject:coordVal];
}
free(coords);
return [NSArray arrayWithArray:coordsArray];
}
+ (MKPolygon *)polygonFromCoordsArray:(NSArray *)coordsArray pointCount:(int)count
{
CLLocationCoordinate2D *coords = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D) * count);
for (int i = 0; i < count; i++) {
CLLocationCoordinate2D coord;
[[coordsArray objectAtIndex:i] getValue:&coord];
coords[i] = coord;
}
free(coords);
return [MKPolygon polygonWithCoordinates:coords count:count];
}
Run Code Online (Sandbox Code Playgroud)
我可以在保存或加载模型实例之前在我的MKPolygon对象上调用这些方法,但是我想在模型本身中覆盖动态getter和setter,这样我就可以说类似的东西[turf setTurf_bounds:polygon](其中polygon是一个MKPolygon实例).
我真正喜欢的是能够做这样的事情:
- (void)setTurf_bounds:(id)turf_bounds
{
MKPolygon *poly = (MKPolygon *)turf_bounds;
NSArray *coordsArray = [Turf coordsArrayFromMKPolygon:poly pointCount:[poly pointCount]];
// Save the converted value into the @dynamic turf_bounds property
}
- (id)turf_bounds
{
// grab the contents of the @dynamic turf_bounds property into say, NSArray *coordsArray
return [Turf polygonFromCoordsArray:coordsArray pointCount:[coordsArray count]];
}
Run Code Online (Sandbox Code Playgroud)
但到目前为止我还没有快乐.调用[super setValue:coordsArray forKey:@"turf_bounds"]或它的getter对应物不起作用,也不会尝试将其写为self.turf_bounds(它只是递归调用我重写的setter).
我是以完全错误的方式解决这个问题,还是只是遗漏了什么?
Mar*_*ger 76
永远不要在NSManagedObject子类中调用[super valueForKey:..]!(除非您自己在超类中实现它们)而是使用原始访问器方法.
ADC的 get getter/setter实现示例:
@interface Department : NSManagedObject
@property(nonatomic, strong) NSString *name;
@end
@interface Department (PrimitiveAccessors)
- (NSString *)primitiveName;
- (void)setPrimitiveName:(NSString *)newName;
@end
@implementation Department
@dynamic name;
- (NSString *)name
{
[self willAccessValueForKey:@"name"];
NSString *myName = [self primitiveName];
[self didAccessValueForKey:@"name"];
return myName;
}
- (void)setName:(NSString *)newName
{
[self willChangeValueForKey:@"name"];
[self setPrimitiveName:newName];
[self didChangeValueForKey:@"name"];
}
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13016 次 |
| 最近记录: |