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


基础教程推荐
- :hover 状态不会在 iOS 上结束 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- 固定小数的Android Money Input 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01