swift - Got delegate nil error even it was set in the main viewcontroller -
i have simple app welcomevc shows greeting message person's name. in vc namevc, users can change name want called, , supposes update name on welcomevc when click back.
in order pass name namevc welcomevc, set protocol changenamedelegate in namevc, , created variable in class:
protocol changenamedelegate { func updatename(name: string) } class nameviewcontroller: uiviewcontroller { @iboutlet weak var nametextfield: uitextfield! var changenamedelegate: changenamedelegate! override func viewdidload() { } @ibaction func closenamevc(_ sender: uibutton) { if let newname = nametextfield.text { changenamedelegate.updatename(name: newname) } dismiss(animated: true, completion: nil) } }
in welcomevc, have made sure register delegate , conforms protocol setting follows:
class welcomeviewcontroller: uiviewcontroller, uiviewcontrollertransitioningdelegate { let namevc = nameviewcontroller() override func viewdidload() { namevc.changenamedelegate = self } } extension welcomeviewcontroller: changenamedelegate { func updatename(name: string) { print("the name has been updated!") namelabel.text = name } }
however when ran app, got crash because changenamedelegate appeared nil. know missed there? in advance!
it seems instantiating new instance of nameviewcontroller when routing welcomeviewcontroller. should navigate namevc instantiated before.
Comments
Post a Comment