Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read String from NSUserDefaults

I have an object at the root of plist that stores objects and keys (one of which is input from a user textfield). I have no problem writing and creating structure; it's trying to read values that causing problem. Below code I used to write the data, can someone tell me how to read the string [val] and [myKey]?

thank you!

#define defaultValue @"Your Name"
#define myKey @"PersonName"

- (void)textFieldAction:(id)sender {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *val;

    // Get the new value from the textfield

    val = [myTextField stringValue];

    if ([val isEqualToString:defaultValue]) {
        [defaults removeObjectForKey:myKey];
    } else {
        // [defaults setObject:val forKey:myKey];

    NSDictionary *my_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                             @"Name", @"PersonName",
                             @"Email", @"PersonEmail", 
                             @"Dept", @"PersonDept", 
                             @"Job", @"PersonJob", 
                             val, myKey, 
                             @"Status", @"PersonStatus", 
                             nil];

    [defaults setObject: my_dict forKey: @"Person"];

    [[NSUserDefaults standardUserDefaults] registerDefaults:my_dict];

I would like to automatically populate the textfield with the [val], for [myKey], if the user has the info already in the plist. Here's the code I'm trying to use for that:

- (void)applicationDidFinishLaunching:(NSNotification *)notification {

    NSUserDefaults *defaults = [[NSUserDefaults standardUserDefaults] objectForKey:myKey];
    NSString *val = [defaults stringForKey:myKey];

    if (val == nil) val = defaultValue;
    [myTextField setStringValue:val];
like image 295
Devon Avatar asked Feb 29 '12 13:02

Devon


1 Answers

You can write the value into NSUserDefault like the following:

[[NSUserDefaults standardUserDefaults] setValue:[myTextField stringValue] forKey:@"Person"];

And read it later like the following:

[myTextField setStringValue:[[NSUserDefaults standardUserDefaults] stringForKey:@"Person"];

So you can simplify your code into:

- (void)textFieldAction:(id)sender {
    [[NSUserDefaults standardUserDefaults] setValue:[myTextField stringValue] forKey:@"Person"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

You can set a default value with the registerDefaults:. And when you can retrieve that value simply by calling:

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    // ...
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"Person", defaultValue}]
    NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:@"Person"];
    [myTextField setStringValue:value];
    // ...
}
like image 97
sch Avatar answered Nov 02 '22 21:11

sch