I used NSUserDefaults to store a value. I store some integer value in NSUserDefaults like as follows in first view.
I declared in interface file as follows..
NSUserDefaults *prefs;
@property(nonatomic,retain) IBOutlet NSUserDefaults *prefs;
Then I used in class file as follows
@synthesize passwordfield,prefs;
here passwordfield is the name of UITextField
NSInteger myInteger = [passwordfield.text integerValue];
[prefs setInteger:myInteger forKey:@"integerKey"];
[prefs synchronize];
NSInteger myInt = [prefs integerForKey:@"integerKey"];
NSLog(@"My integer Value: %d",myInt);
Then I move to next view using navigation controller.
But I can’t read NSUserDefaults’s value from the first view.
I used code like as follows in second view.
PasswordCheckViewController *nextController = [[PasswordCheckViewController alloc] initWithNibName:@"PasswordCheckViewController" bundle:nil];
NSLog(@"Pass in Next: %d",[nextController.prefs integerForKey:@"integerKey"]);
But the output as follows.
Pass in Next: 0
How can I get the value from the first view to second view using NSUserDefaults?
What you are doing is wrong,
NSUserDefaultsare notIBOutlets,anIBOutletis used to refer an InterfaceBuilder control.NSUserDefaultis usually used to store some preference values.Typically, you use the
NSUserDefaultsclass by invoking thestandardUserDefaultsclass method to get an NSUserDefaults object. This method returns a globalNSUserDefaultsobject with a search list already initialized. Use theobjectForKey:andsetObject:forKey:methods to get and set default values. Note that a default’s value can be only property list objects:NSData,NSString,NSNumber,NSDate,NSArray, orNSDictionaryIn your case you are creating an
IBOutletwhich is not needed. Do like thisthis will give you a synchronized
NSUserDefaultsso that you dont need to store anything as an ivar.You can access the value of the object from any classes inside your app