How to get the nsuserdefault value in other viewco

2020-02-17 10:56发布

I have two viewcontrollers. In my first viewcontroller:

{           
    NSString *string=textField.text;  
    NSUserDefaults *data = [NSUserDefaults standardUserDefaults];  

    [data setObject:string forKey:@"strings"];
    [data synchronize];
}   

How do I get the string value in my other viewcontroller?

4条回答
冷血范
2楼-- · 2020-02-17 11:05

you can access NSUserDefaults in any controller (Any class of your application) of your application with the same code you have written in one class.

for getting the string value use the below code

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];  
NSString *myString = [data objectForKey:@"strings"];
查看更多
爷、活的狠高调
3楼-- · 2020-02-17 11:07

In the other ViewController,

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

This will work because NSUserDefaults are a global key-value store that will persist across classes and applications.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-17 11:09
NSUserDefaults * defaults =  [NSUserDefaults standardUserDefaults]; 
NSString *myString = [defaults stringForKey:@"strings"];

THis is the way to retrieve the data. Please note NSUserDefault is not used to pass data between two controllers. There are better methods for that.

Edit : After seeing Shaan Singh's comment

To pass data 2 view controllers you can declare a property in second view controller and access that from the present view controller.

It is already answered brilliantly here.

查看更多
Explosion°爆炸
5楼-- · 2020-02-17 11:17

Here you can use this in anyway in your application for store 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 this in anyway in your application for get 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"];
查看更多
登录 后发表回答