向我的plist文件添加一个新的字典

4

Root ---- Array
  Item 0- Dictionary
    fullName ---- String
    address ---- String
  Item 1 ---- Dictionary
    fullName ---- String
    address ---- String

I have a plist that looks like the one about. In a View I have a button that when clicked I'd like to add a new "Item 2" or 3 or 4 or 5 etc... I just want to add a few more names and addresses.

I've spent 3 hours tonight searching for the perfect example but came up short. The Apple property lists samples were way too deep. I've seen code that probably will come close.

Thanks So Much

NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary]; [nameDictionary setValue:@"John Doe" forKey:@"fullName"]; [nameDictionary setValue:@"555 W 1st St" forKey:@"address"];

NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:[self dataFilePath]];
[plist addObject:nameDictionary];
[plist writeToFile:[self dataFilePath] atomically:YES];

- (NSString *)dataFilePath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"children.plist"]; return path; }

1个回答

8
假设 plist 以文件形式存储在磁盘上,您可以通过调用 arrayWithContentsOfFile 方法重新打开并加载新内容。
// Create the new dictionary that will be inserted into the plist.
NSMutableDictionary *nameDictionary = [NSMutableDictionary dictionary];
[nameDictionary setValue:@"John Doe" forKey:@"fullName"];
[nameDictionary setValue:@"555 W 1st St" forKey:@"address"];

// Open the plist from the filesystem.
NSMutableArray *plist = [NSMutableArray arrayWithContentsOfFile:@"/path/to/file.plist"];
if (plist == nil) plist = [NSMutableArray array];
[plist addObject:nameDictionary];
[plist writeToFile:@"/path/to/file.plist" atomically:YES];

-(void)addObject:(id)object方法总是将对象插入到数组的末尾。如果您需要在特定索引处插入对象,请使用-(void)insertObject:(id)object atIndex:(NSUInteger)index方法。

[plist insertObject:nameDictionary atIndex:2];

谢谢。这样更容易理解了。我在想它如何处理换行符。非常感谢。我现在将前去尝试这个。 - Mike Martin
获取数据超时。变量显示可能不准确。 获取数据超时。变量显示可能不准确。 获取数据超时。变量显示可能不准确。 - Mike Martin
这段代码似乎可以工作,但它没有将值放入我的项目中的.plist文件中。我在项目的资源“文件夹”中有children.plist文件(与我存储png和xib文件的位置相同)。我的代码是...请参见我原始帖子中的上文。 - Mike Martin
我正在将所有的@"/path/to/file.plist"更改为@"filename.plist",它是资源文件夹根目录中的一个plist文件。代码没有出错,但新值未被插入到plist中。有什么想法吗??我可以读取plist来构建我的tableview,这有点奇怪。 - Mike Martin
我刚学到,当你编辑一个plist而不是写入它时,你必须将它存储在隐藏的“文档”目录中。 - Mike Martin
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接