objective-c updating data from a different view

2019-06-11 06:03发布

问题:

I'm using a navigation based view controller in my app. Users can click on a button in the navigation to open a new view where they can select from a few different options. What I'd like to happen is when the user returns to the original view, the app saves the option chosen in the second view in an object in the original view.

I've tried a few things but none of them work.

I've tried creating an object in the original view controller, turning it into a property:

@property (nonatomic, retain) NSString *testing;

then in the second view controller, updating it with something like this when the user selects an option:

if (!oVC)
    oVC = [[OriginalViewController alloc] init];

oVC.testing = object;

I can't get it to work. Could someone point me in the right direction? It would be greatly appreciated.

回答1:

Use NSUserDefaults

In one class:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]
[prefs setInteger:1 forKey:@"integerKey"];

In another class:

 NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
 NSInteger myInt = [prefs integerForKey:@"integerKey"];

//Now myInt has the value 1.

Check for the Documentation here !

You could also have NSNotification and pass an NSDictionary type:

NSDictionary *info = [NSDictionary dictionaryWithObject:@"Brad Pitt" forKey:@"User Name"];


[[NSNotificationCenter defaultCenter] postNotificationName:@"UserNameNotification" object:self userInfo:info];

And then you could add observers and write the method for the corresponding Selector.