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

例如,对于一个具有自定义初始化逻辑的UIView子类,以下情况是否正确?

@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,如in this documentation所述,该方法为initWithFrame:.在这种特殊情况下,您只需要覆盖initWithFrame;所有其他调用最终都将级联并命中此方法.

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

- (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;
}

Objective-c相关问答推荐

如何在 NSImage CIFilter ObjC 周围创建边框

viewWillAppear,viewDidAppear 没有被调用,没有触发

为什么在目标 c 的静态上下文中允许 self

在@implementation 而不是@interface 定义的类变量?

在 UITableViewCells 上显示复制弹出窗口的简单方法,如地址簿应用程序

静态和动态单元格的 UITableView 混合?

将长格式的 NSString 拆分为多行

UIDatePicker,根据今天的日期设置最大和最小日期

动态转发: suppress Incomplete Implementation 警告

[Facebook-iOS-SDK 4.0]如何从FBSDKProfile获取用户邮箱

arc4random 和 arc4random_uniform 有什么区别?

UIBezierPath 减go 路径

判断是否已实现可选协议方法

允许用户从 UILabel 中 Select 文本进行复制

将 NSDate 舍入到最接近的 5 分钟

如何根据按钮按下重新加载/刷新 UIPickerView(带有新数据数组)?

Xcode中私有方法的单元测试

Objective-C:如何向 NSURL 添加查询参数?

未调用 cellForItemAtIndexPath 但 numberOfItemsInSection 调用

UITableViewCell中的文本居中对齐问题