Property 'self.delegate' not initialized a

2019-02-21 01:07发布

After upgrading to Swift 3 I now get this error:

Property 'self.delegate' not initialized at super.init call

On NSObject Class defined

open class NSObject : NSObjectProtocol {
   public init()  
}

IQKeyboardReturnKeyHandler class

public override init() {
   super.init()    //Error here
}

public init(controller : UIViewController) {
   super.init()    //Error here
   addResponderFromView(controller.view)
}

Any suggestions on how to correct this?

标签: ios swift3
1条回答
我命由我不由天
2楼-- · 2019-02-21 01:34

I assume that in your class IQKeyboardReturnKeyHandler you have such declaration:

weak var delegate: YourDelegateProtocol

Since it's neither an optional nor an implicitly unwrapped you have to initialize it before calling the initializer of the superclass.

However, using the delegate pattern, it's better to declare your delegate property as an optional:

weak var delegate: YourDelegateProtocol?

In this case it isn't necessary to set the delegate before calling the initializer of the superclass, so your code will look like this:

weak var delegate: YourDelegateProtocol?

public override init() {
    super.init()
    self.delegate = nil
}

public init(controller : UIViewController) {
    super.init()
    self.delegate = controller
    addResponderFromView(controller.view)
}

Important! When using the delegate pattern, always declare your delegate property as weak to avoid reference cycles.

查看更多
登录 后发表回答