是否可以在自定义init方法中调用[super init]? [英] Is it ok not to invoke [super init] in a custom init method?

查看:150
本文介绍了是否可以在自定义init方法中调用[super init]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MKPolyline 子类,我要实现 NSCoding ,即

I have a MKPolyline subblass which I want to implement NSCoding, i.e.

@interface RSRoutePolyline : MKPolyline <NSCoding>

我问一个关于编码c数组的最佳方法的问题,并得到了一个很好的答案。但是,没有在 MKPolyline ,即除了类方法 polylineWithPoints:points 之外,没有其他方法可以提供数据。

I asked a question on the best way to encode the c-array and got an excellent answer. However, there is no init method defined on MKPolyline, i.e. there is no other way to give it data other than its class method polylineWithPoints:points.

这是我的评论是否确定的代码?

Is this code where my comment is ok?

- (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的任何子类。因为MKPolyline是一个NSObject,所以你应该初始化它。

You should call an init method on any subclass of NSObject. Since MKPolyline is an NSObject, you should init it.

但MKPolyline没有方法,没有init。这是Objective C的告诉你,你不能子类化它。

But MKPolyline has no methods and no init. This is Objective C's was of telling you that you can't subclass it.

正如WDUK所建议的,定义自己的类。它跟踪您的列表点,并管理NSCoding以保存和恢复它们。

Instead, as WDUK suggested, define your own class. It keeps track of your list point points, and manages NSCoding to save and restore them as needed.

 @interface RSPolyline: NSObject<NSCoding>

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

 - (MKPolyline*) polyLine;

 @end

您的类可以根据请求生成折线如果性能是一个问题的结果。

Your class can generate a polyline on request, perhaps caching the result if performance is an issue.

一般来说,首先不要继承继承。当你想扩展和改进一个类时,首先考虑组合。

As a rule, don't reach for inheritance first. When you want to extend and improve a class, think first of composition.

这篇关于是否可以在自定义init方法中调用[super init]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆