如何从NSUserDefaults读取字符串

时间:2012-02-29 13:19:58

标签: objective-c macos cocoa nsuserdefaults

我在plist的根目录下有一个对象,用于存储对象和键(其中一个是从用户文本字段输入的)。我编写和创建结构没有问题;它试图读取导致问题的值。下面我用来编写数据的代码,有人能告诉我如何读取字符串[val]和[myKey]吗?

谢谢你!

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

如果用户已经在plist中有信息,我想自动用[val]为[myKey]填充文本字段。这是我正在尝试使用的代码:

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

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

    if (val == nil) val = defaultValue;
    [myTextField setStringValue:val];

3 个答案:

答案 0 :(得分:34)

您可以将值写入NSUserDefault,如下所示:

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

稍后阅读以下内容:

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

因此,您可以将代码简化为:

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

您可以使用registerDefaults:设置默认值。只需通过调用:

即可检索该值
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    // ...
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"Person", defaultValue}]
    NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:@"Person"];
    [myTextField setStringValue:value];
    // ...
}

答案 1 :(得分:2)

如果我理解正确,你应该只需要做你需要的事情:

NSString * val = [[NSUserDefaults standardUserDefaults] objectForKey: myKey];
[textfield setText: val];

NSUserDefaults Reference Page

答案 2 :(得分:1)

myTextField.text = [[NSUSerDefaults standardUserDefaults] objectForKey:myKey];