0

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.

Plaidfox
  • 55
  • 1
  • 10

1 Answers1

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.

Legolas
  • 12,145
  • 12
  • 79
  • 132
  • Um... I have a question. Now that I'm using it, whenever I rebuild it from xcode, I get the same data I had when I closed out of the simulator. I'm just looking to pass data from one view to another. Is that not what UserDefaults is for? – Plaidfox Jun 18 '11 at 00:21
  • Well.. Every time you rebuild the app, it compiles itself again. So the value should be the same as you had specified in the code. To put in a simple way... if you navigating between two views, and you want the value to pass forward, use NSUserDefaults. If you are communicating backwards, use NSNotifications. – Legolas Jun 18 '11 at 02:48
  • User defaults are persistent. You need to reset them on application startup in your delegate if this the scenario you want. – raidfive Jun 28 '11 at 16:46