在Swift 3中覆盖UIViewController init

时间:2017-05-15 14:34:57

标签: ios objective-c swift uiviewcontroller swift3

在Objective-C应用程序中,当从另一个类初始化类时,我对loadData进行了一些自定义初始化:

- (id)init {
    self = [super init];
    if (self) {
        [self loadData];
    }
    return self;
}

我需要这个来添加更多数据:

MyViewController *vc = [(MyViewController*)[MyViewController alloc]init];
[vc addMoreData: data]; 

当我尝试将其转换为 Swift 3 时,我对如何做到这一点感到困惑。当我添加init方法时,它迫使我添加参数,我不想要(或者我?)。它也让我添加了必需的init(coder:)。如何简单地初始化ViewController类并在ViewController内覆盖它?

2 个答案:

答案 0 :(得分:1)

在Swift中,类应初始化non-optional方法中的所有initializer属性,或non-optional属性应具有默认值。

对于符合init?(coder:)协议的类,Swift编译器强制添加NSCoding

class MyViewController :UIViewController {

var helpText :String = "" //non-optional property with default value
var data :AnyObject? //Its an optional property, it has nil value by default

init() {

    //initalize all the properties of MyViewController here, before calling super class designated initalizer

    super.init(nibName: "MyViewController", bundle: nil)//Designated initializer, pass nil, for both params if not using NIB

    //Now you have access to self
    self.loadData(data: nil)

}



//This method needs to be implemented as UIViewController conform to NSCoding protocol
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func loadData(data :AnyObject?) {
    //Your own implementation
}

func addMoreData(data :AnyObject?) {
    //Your own implementation
}

}

用法:

let myViewController = MyViewController()
myViewController.addMoreData(data: nil) //pass your data here

阅读代码段中的评论,希望这可以回答您的问题!

答案 1 :(得分:0)

你可以这样做:

class MyViewController : UIViewController {

    required init?(coder aDecoder: NSCoder) {

    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        loadData()
    }
}

然后像这样初始化viewController:

let vc = MyViewController(nibName: "MyViewController", bundle: Bundle.main)
vc.addMoreData(data)

希望它有所帮助!