My delegation pattern works (if my delegate function just has to print statements about the data passed back) (programmatic layout, no IB segues). But the receiver class does not update its UI accordingly. This – I believe – closes out the case, that my delegation pattern is wrong. How is it possible that my UI is not updating? What circumstances usually prevent that? I am dealing manual entries here, no network calls, no large amount of data or anything like that. For example my delegate function is :
class DetailTableViewController: AddVCDelegate {
//delegate function of AddVCDelgate protocol
func didAddLesson(lesson: Lesson) { // my addVC is calling this through delegate
self.lesson = lesson
print("delegate function set navitem title: \(lesson.name!)")//printed out correctly
self.navigationItem.title = lesson.name! //nothing changes
self.tableView.reloadData()// no reload
}
/*Here lesson.name got printed out nicely, navigationItem title does not change accordingly , tableView does not reload data.*/
Back in AddVC ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
let vc = DetailTableViewController()
self.delegate = vc //etc..}
and AddVC uses this function:
func passLesson() {
if let lesson = lesson,
let delegate = self.delegate {
delegate.didAddLesson(lesson: lesson)
}
}
I just posted this little snippet only, because the project is a bit too complicated now to copy here, but I believe this is the relevant part of the code for the problem. I can it update with more details if needed. Thanks in advance!
UPDATE: I have uploaded a simple demo project to GitHub which is reproducing the problem, I hope it helps to see the real cause of the problem. I am still desperatly looking, what I am doing wrong here.
Ok, I have found the solution!
As @Roberto and @matt pointed out, I created a new instance of the delegate VC, so the delegation was basically not working! I was confused, because all the print statements were working in the delegate function. That is not quite enough though.
I also have put addVC.delegate = self
in a wrong method! The Idea of changing this to self.delgate = detailVC
in addVC class, is also wrong.
The correct answer seems to be that in detailVC, when I am moving to AddVC, i do it like this:
@objc func handleEdit() {
let avc = AddVC()
avc.lesson = self.lesson
avc.delegate = self
let nc = UINavigationController(rootViewController: avc)
present(nc, animated: true, completion: nil)
}
This way, by the time AddVC is presented, detailVC already knows, that she is the delegate! Why? Because this way I am telling detailVC, that the addVC I am referring to, is the rootController of the navigationController making the "segue". Because classes are reference type, this way the new instance of addVC will be identical, and referenced to the original. I hope I am understanding this correct. But Working!