I am trying to use a delegate to pass an array of data to the previous view controller. I have decided to use a delegate as my unwind segues are not working (more on that in a previous Stack Overflow post). I have created the delegate performing all of the necessary steps for setting it up.
I have tried some solutions from this Stack Overflow question but a lot of the answers are for things I have already done. Things I have tried:
- Renaming the protocol.
- Renaming the delegate.
- Making the protocol not of type
class
. - Force unwrapping the delegate (this one is interesting - it caused my app to crash even though I know the delegate exists).
I have created the protocol in ViewControllerB
:
protocol ViewControllerBDelegate: class {
func viewControllerB(_ controller: UIViewController, didSelectArray array: [String])
}
I create a variable for the delegate with a weak reference cycle:
weak var viewControllerBDelegate: ViewControllerBDelegate?
I have also called a function from my delegate in didSelectRowAt
:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let strArray = ["Hello", "World"]
viewControllerBDelegate?.viewControllerB(self, didSelectArray: strArray)
}
Then on ViewControllerA
:
class ViewControllerA: UIViewController, ViewControllerBDelegate
In the ViewControllerB delegate function:
func viewControllerB(_ controller: UIViewController, didSelectArray array: [String]) {
print("An array of strings: \(array)")
controller.dismiss(animated: true, completion: nil)
}
In the prepare for segue function:
if let viewControllerB = segue.destination as? ViewControllerB {
viewControllerB.viewControllerBDelegate = self
}
I expected the delegate to print the contents of the array that was passed over by ViewControllerB. It did not work though, and unlike what my code was aiming for, the view controller did not dismiss like it was supposed to.