I have a controller (name : Parent.m) extending UIViewController to which I add another view (controller (name: Child.m) ) which has a table view in it.
On click of one of the rows on the table of Child.m, I want to invoke a method in the Parent.m class. I do not want to create a new instance of Parent.m.
Could somebody explain how I can accomplish this. Do I need to define a protocol between the two? If so can somebody explain me how.
If you’re using a UINavigationController, you can get your hands on the parent view controller by doing something like this in your child view controller.
If you are not using a UINavigationController, you could use notifications (may be overkill). Or Key Value Observing from the parent into the child (i.e. change the display or value of something based on a change in the child view controller).
Or, probably the most straightforward thing to do here is set the parent to be a delegate target of the child.
1 )
In your ChildViewcontroller.h file, create a protocol which looks something like this:
2)
Create a delegate property in your ChildViewcontroller (which you’ll set to be the parent view).
3)
In your ParentViewcontroller.h file, add “
<ChildViewDelegate>” after theUIViewController@interface declaration… i.e.4)
Implement the “
doSomethingWith:” method.5)
And when you instantiate / create the Child Viewcontroller from the parent, don’t forget to set the delegate to the parent.
6)
Lasty, when you want to send a message from the child to the parent, it could be as simple as: