在 Objective-C 中读取和更新 plist

Read and Update plist in Objective-C

我想让用户在登录页面选择是否存储用户名,所以我的 plist 有 2 个键:userIsSaved(bool),和 用户名(字符串)
这是我的脚本:

NSString *path = [[NSBundle mainBundle] pathForResource:@"userinfo" ofType:@"plist"];
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
BOOL userIsSaved = [[plistDic objectForKey:@"userIsSaved"] boolValue];
NSString *username = plistDic[@"username"];

if (lg.saveUserSwitch.isOn){

    if (userIsSaved == false){

        [plistDic setObject:[NSNumber numberWithBool:YES] forKey:@"userIsSaved"];
        plistDic[@"username"] = lg.usernameFld.text;

        [plistDic writeToFile: path atomically: YES];

        if ([plistDic writeToFile: path atomically: YES] == NO) {
            NSLog(@"!!!Save plist file failed");
        }

    }

}

我有一些问题:

  1. 为什么我不能写plistDic[@"userIsSaved"] = true来更新bool值?如何正确更新呢? [plistDic setObject:[NSNumber numberWithBool:YES] forKey:@"userIsSaved"] 好像改了类型吧。我该如何阅读?
  2. 我无法将 plistDic 写入 plist。不知道是什么问题

回答

  1. 您不能将布尔值(或整数或浮点数或...)存储到字典中 - 只能存储对象。所以你需要先将它转换为一个对象,在本例中,NSNumber 就像你所做的那样。您也可以使用快捷方式 plistDic setObject:@(YES) forKey:@"userIsSaved"]

  2. 要写入,首先获取正确目录的路径,通常类似于

    NSURL * dir = [[NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory
                                inDomains:NSUserDomainMask].firstObject
               URLByAppendingPathComponent:NSBundle.mainBundle.bundleIdentifier
               isDirectory:YES];

然后你可以使用类似 NSString * myFile = [dir.path stringByAppendingPathComponent:@"mylist.plist"];

然后改为写入 myFile

还请注意,使用 URL 可能是个好主意。