【问题标题】:Cannot edit a dictionary after reading it from a plist从 plist 读取字典后无法编辑字典
【发布时间】:2012-05-23 09:47:48
【问题描述】:

我将 NSMutableDictionary 存储在 plist 文件中。 当我将它读入对象的属性时,我需要能够对其进行编辑。 我的属性指针仅是 NSMutableDictionary, 但是从 plist 生成的对象是 NSDictionary。

现在我希望能够添加更多键值对或删除一些键值对并再次保存。 我不能,因为它现在是一个不可变的对象。

对象是在我的模型的 init 中创建的。

我该怎么办?

【问题讨论】:

    标签: objective-c ios plist nsmutabledictionary


    【解决方案1】:

    这应该可以满足您的需要:

    NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile: <myfilename>];
    NSMutableDictionary * mutableDict = [[dict mutableCopy] autorelease];
    

    【讨论】:

    • NSDictionary 的任何方法都可以在NSMutableDictionary 上调用,包括便利构造函数。然后,便利构造函数返回NSMutableDictionary 的实例(或类簇中的具体子类)。所以,你可以做NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithContentsOfFile: &lt;myfilename&gt;];
    【解决方案2】:

    这就是你需要做的一切

    NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
    

    【讨论】:

      【解决方案3】:

      您只需要制作字典的可变副本:

      NSDictionary *dictionary;
      
      NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
      

      【讨论】:

        猜你喜欢
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 1970-01-01
        • 2012-11-24
        • 1970-01-01
        相关资源
        最近更新 更多