Recently when developing an iOS app, I encountered a problem that i need to have two view controllers to share some data, or even retrieve UI status from another view controller.
To honor this feature, i defined and implemented delegate for view controllers.
@protocol ViewControllerADelegate <NSObject>
-(id)dataForSomePurposeForViewController:(ViewController *)viewController
@end
and then when pushing a new viewController(in ViewControllerA) class, I will set the currentViewController as delegate of the new controller if it is needed.
viewControllerA.delegate = currentViewController
[currentViewController.navigationController pushViewController:viewControllerA animated:YES]
After that I can call the delegate selector and get data from last view controller like:
//in viewControllerA
self.someData = [self.delegate dataForSomePurposeForViewController:self]
The code above is just an example showing what i have tried, there may be some typo in the code and do not pay too much attention to it.
In fact the above way works fine and never causes any problem up to now. But when i talked about this with one of my colleague, who is an Android developer, I was told that what i have done in iOS will not work in Android. In the task stack model in Android, the view controller (called Activity in Android) will not execute any code or respond to any function call when it is not at the top of the navigation stack.
This somehow makes me worry about my usage of delegate in this way. I googled a lot and now I know that my implementation is little bit against the MVC design pattern and the best way for communication between view controllers may be setting a shared model.
However changing the current code is a time consuming task. So My question is:
- What is the risk of using delegate for view controller communication?
- Is that as I understood that having a shared model to is the best practice? If yes, who should i assign this model to? by using singleton?
Any help or thinking is appreciated and thanks in Advance.