在子类中覆盖init

Overriding init in subclass(在子类中覆盖init)

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

问题描述

在Objective-C中,是否需要重写子类的所有继承构造函数来添加自定义初始化逻辑?

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

例如,对于具有自定义初始化逻辑的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在子类中覆盖init

基础教程推荐