How to get nsuserdefault value in other viewcontrollers

I have two view managers. In my first view manager:

{ NSString *string=textField.text; NSUserDefaults *data = [NSUserDefaults standardUserDefaults]; [data setObject:string forKey:@"strings"]; [data synchronize]; } 

How to get string value in my other view manager?

+8
ios objective-c cocoa-touch uiviewcontroller
source share
4 answers

Here you can use this anyway in your application to store the value of NSUserDefaults.

 // --- Saving NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // saving an NSString [prefs setObject:@"TextToSave" forKey:@"keyToLookupString"]; // saving an NSInteger [prefs setInteger:42 forKey:@"integerKey"]; // saving a Double [prefs setDouble:3.1415 forKey:@"doubleKey"]; // saving a Float [prefs setFloat:1.2345678 forKey:@"floatKey"]; // This is suggested to synch prefs, but is not needed (I didn't put it in my tut) [prefs synchronize]; 

Here you can use it anyway in your application to get the value of NSUserDefaults.

 // --- Retrieving NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; // getting an NSString NSString *myString = [prefs stringForKey:@"keyToLookupString"]; // getting an NSInteger NSInteger myInt = [prefs integerForKey:@"integerKey"]; // getting an Float float myFloat = [prefs floatForKey:@"floatKey"]; 
+22
source share
 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; NSString *myString = [defaults stringForKey:@"strings"]; 

This is a way to get data. Note that NSUserDefault not used to transfer data between two controllers. There are more effective methods for this.

Edit: After watching a comment by Shaan Singh

To pass data controllers 2, you can declare a property in the controller of the second view and access it from the current view controller.

He already answered brilliantly here .

+4
source share

You can access NSUserDefaults in any controller (any class of your application) of your application with the same code that you wrote in the same class.

use the code below to get the value of a string

 NSUserDefaults *data = [NSUserDefaults standardUserDefaults]; NSString *myString = [data objectForKey:@"strings"]; 
+4
source share

In another ViewController,

 NSUserDefaults *data = [NSUserDefaults standardUserDefaults]; NSString *string = [data objectForKey:@"strings"]; 

This will work because NSUserDefaults is a global keystore that will be stored in classes and applications.

+3
source share

All Articles