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....
There are a lot of options for communicating between parent and child view controllers:
Parent -> child
Child -> parent
UIApplicationDelegate
)NSUserDefaults
The excellent detailed explanation
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With