Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better approach to communicate between parent and child view controllers?

It may be a simple way, but I need some guidance from those who have been familiar with iOS.

If a parent view controller want to send one particular message to all child view controllers, what is the best way?, Still now I have wrote a method in each child view controller and informed whenever necessary, In a situation I want to notify to all childs? What should I do for this? I don't think I need to write the same method in all ViewControllers..

or

Do I need to go for subclassing.... thanks....

like image 395
Newbee Avatar asked Jun 17 '13 09:06

Newbee


3 Answers

There are a lot of options for communicating between parent and child view controllers:

  1. Parent -> child

    • Direct interaction: there is an instance in the parent
  2. Child -> parent

    • Delegation [preferred]
    • Notification
    • Pass value via database, Plist file etc.
    • Store in an app delegate instance and pass the value (UIApplicationDelegate)
    • NSUserDefaults

The excellent detailed explanation

like image 150
Lithu T.V Avatar answered Nov 15 '22 06:11

Lithu T.V


If you simply want to invoke a method on your child view controllers, you could use:

[[self childViewControllers] makeObjectsPerformSelector:@selector(nameOfSelector:) withObject:objectToSend];

or one of the other methods for passing objects along with your selector.

As @Gianluca Tranchedone suggested, you could use delegates or an observer pattern but it really depends on what you need to do and how your code is structured. Making your parent view controller conform to delegates of your child view controllers would allow you to structure your code in a much cleaner way.

like image 33
Zack Brown Avatar answered Nov 15 '22 06:11

Zack Brown


Use the delegation pattern. You specify some methods that you want your delegate to implement as a protocol and have your parent view controller implement the protocol. Your children view controllers can have a property called 'delegate' of type 'id' where MyDelegateProtocol is the protocol you specify. Then, when you want your children view controllers to talk to the parent you can call the methods specified in the protocol. For example, if your protocol specify a method called 'myMethod', in you child view controller you can call [self.delegate myMethod].

Using this approach you can have your children asking information to the parent. If you want to notify children of something that has happened, instead, you better use notifications (NSNotification) or have your children view controllers to observe some property of their parent.

Checkout this guide from Apple called Working With Protocols for more information on how to use them.

like image 25
Gianluca Tranchedone Avatar answered Nov 15 '22 06:11

Gianluca Tranchedone