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
- GPS状态的广播接收器? 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- URL编码Swift iOS 2022-01-01
- UITextView 内容插图 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01