gpt4 book ai didi

ios - 可以不在自定义 init 方法中调用 [super init] 吗?

转载 作者:行者123 更新时间:2023-12-01 17:57:24 29 4
gpt4 key购买 nike

我有一个 MKPolyline我要实现的 subblas NSCoding , IE。

@interface RSRoutePolyline : MKPolyline <NSCoding>

I asked a question on the best way to encode the c-array and got an excellent answer .但是, MKPolyline 上没有定义 init 方法。 ,即除了它的类方法 polylineWithPoints:points 之外没有其他方法可以给它数据.

这段代码我的评论可以吗?
- (void)encodeWithCoder:(NSCoder *)aCoder
{
MKMapPoint *points = self.points;
NSUInteger pointCount = self.pointCount;

NSData *pointData = [NSData dataWithBytes:points length:pointCount * sizeof(MKMapPoint)];
[aCoder encodeObject:pointData forKey:@"points"];
[aCoder encodeInteger:pointCount forKey:@"pointCount"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
NSData* pointData = [aDecoder decodeObjectForKey:@"points"];
NSUInteger pointCount = [aDecoder decodeIntegerForKey:@"pointCount"];

// Edit here from @ughoavgfhw's comment
MKMapPoint* points = (MKMapPoint*)[pointData bytes];

// Is this line ok?
self = (RSRoutePolyline*)[MKPolyline polylineWithPoints:points count:pointCount];

return self;
}

最佳答案

您应该在 NSObject 的任何子类上调用 init 方法。由于 MKPolyline 是一个 NSObject,你应该初始化它。

但是 MKPolyline 没有方法,也没有 init。这是Objective C的意思是告诉你你不能继承它。

相反,正如 WDUK 建议的那样,定义您自己的类。它跟踪您的列表点,并管理 NSCoding 以根据需要保存和恢复它们。

 @interface RSPolyline: NSObject<NSCoding>

- (id) initWithPoints: (NSArray*) points;
- (id) initWithCoder:(NSCoder *)aDecoder;
- (void) encodeWithCoder:(NSCoder *)aCoder;

- (MKPolyline*) polyLine;

@end

您的类可以根据请求生成折线,如果性能有问题,可能会缓存结果。

作为一项规则,不要先获得继承权。当你想扩展和改进一门课时,首先要考虑作文。

关于ios - 可以不在自定义 init 方法中调用 [super init] 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14914265/

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