Overriding init in subclass(在子类中覆盖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
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01