简体   繁体   English

iOS-将项目添加到plist

[英]iOS - Adding items to plist

I'm writing a plist from an 'NSMutableDictionary'. 我正在从“ NSMutableDictionary”编写一个列表。 That works ok. 没关系。

But when I want to add to the file, the new entry overrides the first entry. 但是,当我要添加到文件中时,新条目将覆盖第一个条目。

What I'd like is something like this: 我想要的是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<names>
<name1>
    <key>
        firstname
    </key>
    <value>
        mememememe
    </value>
    <key>
        lastname
    </key>
    <value>
        mememememe
    </value>

</name1>
<name2>
    <key>
        firstname
    </key>
    <value>
        mememememe
    </value>
    <key>
        lastname
    </key>
    <value>
        mememememe
    </value>

    </name2>
</names>
Here's my code so far:



    NSString *filename = [documents stringByAppendingPathComponent:@"faves.plist"];
    NSMutableDictionary *loadedMiscDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:filename];

 NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [directories firstObject];

    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
    [tempDict setValue:firstNameString forKey:@"firstname"];
    [tempDict setValue:secondNameString forKey:@"secondName"];

  [loadedMiscDictionary addEntriesFromDictionary:tempDict];
    [loadedMiscDictionary writeToFile:filename atomically:YES];

Please let me know what I'm doing wrong. 请让我知道我在做什么错。 TIA TIA

UPDATE 更新

I changed my code snippet above.. 我在上面更改了代码段。

Your code overrides the old entries of the plist. 您的代码将覆盖plist的旧条目。 You are not getting plist file entries in dictionary. 您没有在字典中获得plist文件条目。 Just create a new dictionary add some new entries and override old file. 只需创建一个新词典,添加一些新条目并覆盖旧文件即可。

  • fetch plist file data 获取plist文件数据
  • stored it in NSMutableDictionary or NSMutableArray 将其存储在NSMutableDictionary或NSMutableArray中
  • Add new entries in that dict. 在该字典中添加新条目。 or array 或数组
  • At the last get current file location and stored that newly created dict. 最后获取当前文件位置并存储该新创建的字典。 or array which carry old and new entries in it. 或数组,其中包含新旧条目。

I hope it will helps you 希望对您有帮助

您应该使用右键单击+添加行作为顶级类别,对于子类别使用+符号在plist文件中添加新的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM