one of my view controllers has several UISwitches, and I want another view Controller to be able to access the values of the UISwitches for If/and statements. How do I do this in Objective-c?
问题:
回答1:
You probably don't want to do that. If you want a second ViewController to have different behavior based on switches thrown in the first, you should just bind the switches to User Defaults, which you can read anywhere in your app.
http://icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/
回答2:
This is a bad idea as it would create an unneeded dependency between the view controllers.
If you still want to do it, just pass a reference of the first view controller with the switches to the second view controller. Then, in your second view controller just access the corresponding UISwitch's on
property.
However, instead of going that route, I strongly suggest that you create a custom class to hold the boolean state of each UISwitch. An instance of this class could either be a singleton, or contained in the application delegate. See this answer for how to do it with both approaches.
A custom class is better because a UISwitch is just a way to represent some property in your data model. And if tomorrow you replaced the UISwitch with another fancy control, the second view controller should still continue to work. Both view controllers have a reference to an object of this custom class. Whenever there is a change, the first controller updates this object.
The class interface could be something like this:
@interface DataValues : NSObject {
BOOL first;
BOOL second;
BOOL third;
}
@property BOOL first;
@property BOOL second;
@property BOOL third;