问题
I have a fairly complex application at this point, and feel as though the way I am handling data is not up to scratch.
So I have started taking some steps towards making my app more MVC friendly. The first of which, I have gone from having inline parser methods in all of my ViewControllers to creating a dedicated parser class.
Its not hard to call I just set up the class then call the initializer method I have made which I pass the data to for my request.. everything in my object class works sweet I get a whole bunch of return data from the server that I am parsing.. but then this is where I get abit lost.
How do I get that data back to the ViewController that called it? I have worked a little with protocols and delegates.. but I dont know how that would fit into this.
Here is an graphical example of what I am trying to achieve.
![](https://i0.wp.com/i.stack.imgur.com/zEyOC.png)
So as above View controller calls the initalization method of the object class which connects to the DB downloads the data, and then parses that data. The issue I am having is how do I then get that data to ViewController2..
what is the most appropriate and future proof way of doing this?
回答1:
A custom -init
method does wonders. For instance, I needed to instantiate and push a picker preloaded with the array from the previous screen, so I defined -(id)initWithArray:(NSArray*)array
in the second view, then just called secondView = [[SecondView alloc]initWithArray:_population];
then pushed it. Remember to get ownership of any object you pass before it is deallocated and destroyed!
回答2:
If you want to broadcast data from your object to all view controllers the good way to do this will be by notifications (NSNotificationCenter). You could also write a methods with completion blocks inside your parser object.
回答3:
Try to send a local notification using NSNotificationCenter. Register your ViewController2 as a listener, then upon receiving the notification, call your data model (singleton!?) for the data.
来源:https://stackoverflow.com/questions/9659065/how-to-pass-data-between-viewcontrollers