Devon Devon - 4 months ago 18
Objective-C Question

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",

[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];

sch sch

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];

And when you can retrieve that value simply by calling:

- (void)applicationDidFinishLaunching:(NSNotification *)notification
    // ...
    NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:@"Person"];
    if (value == nil) value = defaultValue;
    [myTextField setStringValue:value];
    // ...