Reputation: 3400
I have a modal segue to one view controller that has a table view.
When a user selects a cell in that table view, I want the view controller to be dismissed and in the presenting view controller, a variable to be changed to the contents of the cell selected.
How can I change a variable in another view controller programatically? (without using the prepareForSegue method, since I am not doing a segue, but am dismissing the view controller)
Upvotes: 1
Views: 361
Reputation:
This sounds like a bit of a strange pattern (selecting from a table view usually moves forward in navigation) but you can do it this way. Just create a protocol called something like CellSelectNotification
which needs a method that identifies the selected cell (perhaps it takes an indexPath, to keep implementation simple). You make the parent view controller conform to that protocol and give the view controller presenting that table view a reference to its parent as a CellSelectNotification delegate. When the table view has a cell selected you notify the parent of the selected index path through the delegate method you defined, then you allow the view controller to be dismissed.
This is the general way of allowing objects that normally should not have references to each other to communicate - the delegate pattern says "I need some situation to be handled, that handling is delegated
to the receipient - implementation is not important to the caller".
Another way you could do this is via Key-Value Observing or through NSNotification but these last two are a bit heavyweight for the simple notification you want in this case.
Upvotes: 2