gpt4 book ai didi

ios - 是否可以覆盖 NSManagedObject 子类中@dynamic 属性的 getter 和 setter?

转载 作者:IT王子 更新时间:2023-10-29 07:40:53 25 4
gpt4 key购买 nike

所以,我的场景是这样的:

我的 iOS 应用程序中有一个 NSManagedObject 子类,作为一个属性,我想存储 MKPolygon 对象的内容。我决定解决这个问题的方法(它是否有效可能是一个不同的问题)是将多边形属性声明为可转换对象,然后存储一个包含多边形点的 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];
}

我可以在保存或加载模型实例之前在我的 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]];
}

但到目前为止我还没有快乐。调用 [super setValue:coordsArray forKey:@"turf_bounds"] 或其对应的 getter 方法不起作用,尝试将其写为 self.turf_bounds 也不起作用(它只是递归调用我重写的 setter )。

我是不是以完全错误的方式解决了这个问题,还是只是遗漏了什么?

最佳答案

切勿在 NSManagedObject 子类中调用 [super valueForKey:..]! (除非你自己在父类(super class)中实现它们)而是使用原始访问器方法。

来自 ADC 的 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

关于ios - 是否可以覆盖 NSManagedObject 子类中@dynamic 属性的 getter 和 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6007633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com