Passing Object Between View Controllers in Objective C
I have a very simple iPhone view based application I need help on. It's a view based application with a nav. bar in the footer that switches between 4 view controllers.
What I need to do is pass a UILabel value from view 2 to view 4. The UILabel field is a value calculated in view 2, but I want it to appear in view 4 (if 5+5=10, I want the 10 to ap开发者_开发知识库pear in view controller 4, not view controller 2).
How do I go about doing this? Does anyone have any sample code I can review? I've searched awhile in Apple's docs and online and haven't found anything helpful yet. Keep in mind I'm a real newb. when it comes to development. I'm just starting to learn!
Thanks in advance.
There are a few ways. I would probably just have a variable created in the application delegate's interface and just change it and access it there.
NSObject *myVariableFromDelegate = [[[UIApplication sharedApplication] delegate] myVariable];
[[[UIApplication sharedApplication] delegate] setMyVariable:10];
Take a look at NSNotificationCenter. You can send a messages and handle them anywhere in the app, best solution in most similar cases.
The application delegate might work for you, but if you are going to have a lot of values to keep track of, you are probably better off implementing a separate class for your data. Otherwise it will get unwieldy quick.
When you load a new view, you pass off a pointer to the data cass to that view controller so that the current values can be pulled out and put into the correct fields. In addition, you could use register for notifications in the view controller to catch any changes that other views make. Just make sure you de-register the notification when the view unloads, and you should be good.
精彩评论