What is the best approach for exchanging data between parent and child controllers?

It may be an easy way, but I need recommendations from those who are familiar with iOS.

If the parent view controller wants to send one specific message to all the child view controllers, what is the best ?, still I wrote a method in each child view controller and reported when necessary, in a situation where I want to notify all children? 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 look for subclasses .... thanks ....

+4
source share
3 answers

If you just want to call a method on your child controllers, you can use:

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

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

As @Gianluca Tranchedone suggested, you can use delegates or an observer pattern, but it really depends on what you need to do and how your code is structured. Providing the controller with a parent view in accordance with the controller delegates of your child view will allow you to structure your code in a much simpler way.

+4
source

Communication with the parent element of the Viewcontrollers. There are many options.

Parent → Child

  • Direct interaction, the instance is in the parent

Barkers> Parent

  • Delegation [most preferred]
  • Notification
  • The value of the transfer through the database, Plist file, etc.
  • Store in appdelegate instance and pass value [uiapplicationdelegate]
  • NSUserDefaults

The finest detailed explanation

+7
source

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

Using this approach, you can ask your children to request information from the parent. If you want to notify children of something that happened, it is better to use notifications (NSNotification) instead or to force your children to look at controllers to observe some property of their parent.

Check out this Apple tutorial on Working with Protocols for more information on how to use them.

+2
source

Source: https://habr.com/ru/post/1486572/


All Articles