【问题标题】:Changing values in plist - Doesn't change value更改 plist 中的值 - 不更改值
【发布时间】:2023-03-20 09:35:01
【问题描述】:

我正在使用我发现的这个简单方法写入 plist,但它似乎不起作用:

-(IBAction)modifyPlist:(id)sender{

NSBundle *mainBundle=[NSBundle mainBundle];
NSString *path=[mainBundle pathForResource:@"Preferences" ofType:@"plist"];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
[[dict objectForKey:@"Root"] setBool:YES forKey:@"startup"];
}

我做错了什么? 谢谢

【问题讨论】:

    标签: objective-c xcode cocoa


    【解决方案1】:

    您正在将文件加载到内存中并修改该内存,但您没有将其写回磁盘。你会想要使用NSDictionary-writeToFile:atomically:

    [dict writeToFile:path atomically:YES];
    

    Reference link here.

    【讨论】:

      【解决方案2】:

      我希望您确切地知道自己在做什么,这是(无论出于何种原因)您的设计决定 -
      因为您即将写入应用程序包

      这在沙盒下肯定会失败,而且通常是一个坏主意。

      如果您在存储用户默认设置后,请阅读 Mac 存储首选项的方式:
      Preferences and Settings Programming Guide

      【讨论】:

        【解决方案3】:
        // Make a path to the plist in the Documents directory (not the bundle directory)
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Preferences.plist"];
        
        // Then after creating or making changes to your dictionary, write your dictionary out to the plist file
        [dict writeToFile:path atomically:YES];
        

        也许看看: Should I use NSUserDefaults or a plist to store data?

        【讨论】:

          猜你喜欢
          • 2016-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-02
          • 1970-01-01
          相关资源
          最近更新 更多