覆盖子类中的init [英] Overriding init in subclass

查看:97
本文介绍了覆盖子类中的init的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,是否有必要覆盖子类的所有继承构造函数以添加自定义初始化逻辑?

In Objective-C, is it necessary to override all inherited constructors of a subclass to add custom initialization logic?

例如,以下内容对于a是否正确 UIView 具有自定义初始化逻辑的子类?

For example, would the following be correct for a UIView subclass with custom initialization logic?

@implementation CustomUIView

- (id)init {
    self = [super init];
    if (self) {
        [self initHelper];
    }
    return self;
}

- (id)initWithFrame:(CGRect)theFrame {
    self = [super initWithFrame:theFrame];
    if (self) {
        [self initHelper];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self) {
        [self initHelper];
    }
    return self;
}

- (void) initHelper {
    // Custom initialization
}

@end


推荐答案

每个Cocoa Touch(和Cocoa)类都有一个指定的初始值设定项;对于 UIView ,如上所述在本文档中,该方法是 initWithFrame:。在这种特殊情况下,您只需要覆盖 initWithFrame ;所有其他调用将最终级联并最终命中此方法。

Every Cocoa Touch (and Cocoa) class has a designated initializer; for UIView, as stated in this documentation, that method is initWithFrame:. In this particular case, you'll only need to override initWithFrame; all other calls will cascade down and hit this method, eventually.

这超出了问题的范围,但是如果你最终创建一个带有额外参数的自定义初始值设定项,在分配 self 时,你应该确保超类的指定初始值设定项,如下所示:

This goes beyond the scope of the question, but if you do end up creating a custom initializer with extra parameters, you should make sure to the designated initializer for the superclass when assigning self, like this:

- (id)initWithFrame:(CGRect)theFrame puzzle:(Puzzle *)thePuzzle title:(NSString *)theTitle {
    self = [super initWithFrame:theFrame];
    if (self) {
        [self setPuzzle:thePuzzle];
        [self setTitle:theTitle];
        [self initHelper];
    }
    return self;
}

这篇关于覆盖子类中的init的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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