David Choi
David Choi

Reputation: 6619

Object is nil although it was set in init

I have an object called navigator, which I set within init. I break on it to make sure it is set. However when an IBAction func, linkButtonClicked, get's called and try's to use navigator I get a nil exception. Why?

class HomeCollectionViewCell: UICollectionViewCell {
    let appDelegate:AppDelegate!
    let navigator: Navigator!
    @IBOutlet weak var linkButton: UIButton!
    var destinationView:String?
    var parentViewController:UIViewController?

    @IBAction func linkButtonClicked(_ sender: Any) {
        do {
            try self.navigator.navigate(to: self.destinationView!, from: parentViewController!)
        } catch {

        }
    }

    required init?(coder aDecoder: NSCoder) {
        self.appDelegate = UIApplication.shared.delegate as! AppDelegate
        self.navigator = self.appDelegate.navigator

        super.init(coder: aDecoder)
    }

    override func prepareForReuse() {
        super.prepareForReuse()

        // do resetting here if needed, like empty out data
        linkButton.setTitle(nil, for: .normal)
    }
}

Upvotes: 2

Views: 52

Answers (1)

Pedro Castilho
Pedro Castilho

Reputation: 10512

The init?(coder: NSCoder) initializer gets used when you are retrieving the object from some kind of encoded store such as Core Data. This initializer is required by the NSCoding protocol and is used only for deserializing the object. Therefore, it does not get called at object creation. It only gets called if you serialize the object using NSCoding and later deserialize it.

The function you want to override in order to ensure some value will be set in your view is not its init (and if you really want to use its init, the method to overload is init(frame:)). Instead, you should set any variables you want to be available in the viewDidLoad method of the view controller.

Upvotes: 1

Related Questions