I'd like to know too...
When I last looked at accessing a variable between View Controllers (VC), I hit a wall.
In fact, I was fairly discouraged that either I was missing something or there was more to it than met the eye.
I read a posting somewhere to de-reference the target VC using the App Delegate. And I *almost* had it working, but no joy
Because it was iPhone app settings data I was trying to pass between VCs, I ended up using the persistent store of NSUserDefaults, using code like this to save the value when a TextField in one VC completed editing:
Code:
- (void)textFieldDidEndEditing:(UITextField *)theTextField {
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
[defs setObject:[NSString stringWithFormat:@"%1.1f", txtParameter1.text.floatValue] forKey:@"parameter1"];
[defs synchronize];
theTextField.text = [NSString stringWithFormat:@"%1.1f", theTextField.text.floatValue];
}
... and when the target VC is about to come into view, using code like this to read the setting into a variable:
Code:
- (void)viewWillAppear:(BOOL)animated {
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
parameter1 = [[defs stringForKey:@"parameter1"] floatValue];
If you use this approach, be sure to test if the setting is already in persistent storage, and if not to set a default value. Here's what I did in my main VC initializer:
Code:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
if ([defs stringForKey:@"parameter1"] == nil) [defs setObject:@"0.0" forKey:@"parameter1"];
.
.
.
If there is a better way to access variables between View Controllers, assuming it can be done at all, I'm sure both the OP and I would welcome
some demo code, rather than generalized comments to show us how. Thanks very much.