[背景]
对于swift中init函数方面的内容,之前都简单整理过了,但是现在用起来,还是不会用。
只写了个:
init(){ super.init() viewControllers=NSArray() }
就不知道如何处理了。
然后就又报错了:
swift:21:9: Must call a designated initializer of the superclass ‘UIViewController’
如图:
[解决过程]
1.搜:
swift init uiviewcontroller
参考:
结果是写成:
convenience init(){ self.init() viewControllers=NSArray() }
required init(coder aDecoder: NSCoder) {
self.backCardImage = UIImage(named: "back")
self.frontCardImage = UIImage(named: "front")
super.init(coder: aDecoder)
}
但是暂时不去管了。
[总结]
对于swift去写init的话,尤其是继承了UIViewController的类,
此处,没去关心那些复杂的coder之类的。
直接加上convenience:
convenience init(){
self.init()
//add your self other value init code
}
即可。
[后记]
后来,基本算是有点了解了。
常见的一个最最基本的视图控制器的写法,可以写成:
class HomeViewController: UIViewController{ init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLoad() { super.viewDidLoad() //add your code here self.view.backgroundColor = UIColor.whiteColor() } }
其中:
1.必须要实现那个required init?(coder aDecoder: NSCoder)
原因是:
你所继承的UIViewController,其定义中就有:
public class UIViewController : UIResponder, NSCoding, UIAppearanceContainer, UITraitEnvironment, UIContentContainer, UIFocusEnvironment {/*The designated initializer. If you subclass UIViewController, you must call the super implementation of thismethod, even if you aren’t using a NIB. (As a convenience, the default init method will do this for you,and specify nil for both of this methods arguments.) In the specified NIB, the File’s Owner proxy shouldhave its class set to your view controller subclass, with the view outlet connected to the main view. If youinvoke this method with a nil nib name, then this class’ -loadView method will attempt to load a NIB whosename is the same as your view controller’s class. If no such NIB in fact exists then you must either call-setView: before -view is invoked, or override the -loadView method to set up your views programatically.*/public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)public init?(coder aDecoder: NSCoder)
-》
意思是:UIViewController中有两个init初始化函数
由于都没有加前缀optional,则表示都是required必须的,子类必须实现的
所以此处事例代码中:
(1)
init(passInStr:String) {
中,调用到了:
父类的super.init(nibName: nil, bundle: nil)
(2)而虽然此处没有用到,但是也要去实现:
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
才可以。