ios - self init .. 与 super init ... 在子类中

标签 ios objective-c init super

我有一个 UIViewContoller 子类 BaseViewControler。它有一个名为 -initWithStyle: 的方法。如果我将 that 类子类化为 SubBaseViewContoller-[SubBaseViewController init] 应该是什么样子?

我的代码:

- (id)init
{
    self = [self initWithStyle:kGreenStyle];
    if (self) {
        // stuff
    }
    return self;
}

SubBaseViewController 我没有 initWithStyle: 并且我的应用程序使用上面的 -init 随机崩溃,我检查了其他 View Controller ,它们是 BaseViewController 的子类,它们使用 self = [super initWithStyle:kGreenStyle] ,并开始工作。怎么解释?

最佳答案

UIViewController两个指定的初始化器:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle;

- (instancetype)initWithCoder:(NSCoder *)aDecoder;

当使用 Interface Builder 定义带有资源的 View Controller 时,将调用第二种形式,即 nib 文件或 segues。当您手动创建 View Controller 时,可以使用第一种形式。

您可以按如下方式覆盖这些初始化器:

// Designated initializer
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
    self = [super initWithNibName:nibName bundle:nibBundle];
    if (self) {
        ; // your initialization
    }
    return self;
}

// Designated initializer
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        ; // your initialization
    }
    return self;
}

注意:init 方法在从资源创建时不会被调用。当您自己调用 init 时,它最终会使用 nil 参数调用 initWithNibName:bundle:

另请参阅:引用:Multiple Initializers and the Designated Initializer

您的问题的另一种可能的解决方案:

提供初始化自定义 View Controller 的方法的一种方法是使用“便利类方法”。在这种情况下,您不需要重写指定的初始值设定项,而是在您的子类中提供属性

便利类方法可能如下所示:

// MyViewController
+ (instancetype) myViewControllerWithStyle:(Style)style 
{
    // Possibly get the bundle and the nib name (or leave it nil)
    ...
    // Invoke a designated initializer with suitable parameters:
    MyViewController* viewController = [[MyViewController alloc] initWithName:nibName
                                                                       bundle:bundle];
    viewController.style = style;
    return viewController;
}

关于ios - self init .. 与 super init ... 在子类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22528358/

相关文章:

ios - Objective-C:将大多数消息转发给另一个对象(在运行时)

ios - 项目是否必须创建为 sprite 工具包,或者可以简单地添加框架?

ios - 委托(delegate)返回零

objective-c - NSLayoutConstraints 和动态设置 View 的宽度/高度

swift 问题: how can we init an non-optional variable in a if else block if it's of protocol type?

ios - 转换为 Swift 3 错误 : "Convert to Current Swift Syntax Failed Could not find test host for..."

ios - 栏按钮项目图标大小和宽度

Python:具有多个变量的颜色输出

Python 3.5 如何摆脱类函数中的 eval

ios - 相机没有指向我想要使用 SceneKit 的地方