Objective c 如何将字典写入plist中的数组?
我的plist结构如下:Objective c 如何将字典写入plist中的数组?,objective-c,Objective C,我的plist结构如下: <dict> <key>memos</key> <array> <dict> <key>title</key> <string>First Memo</string> <key>content</key> <string>Testing one two th
<dict>
<key>memos</key>
<array>
<dict>
<key>title</key>
<string>First Memo</string>
<key>content</key>
<string>Testing one two three</string>
<key>category</key>
<string>testing</string>
</dict>
<dict>
<key>title</key>
<string>Test</string>
<key>content</key>
<string>This is a test memo.</string>
<key>category</key>
<string>testing</string>
</dict>
</array>
</dict>
self.memos = [NSMutableArray array];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Memos" ofType:@"plist"];
NSDictionary *tempDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *tempArray = [tempDictionary objectForKey:@"memos"];
for(id dict in tempArray) {
NSString *title = [dict objectForKey:@"title"];
NSString *content = [dict objectForKey:@"content"];
NSString *category = [dict objectForKey:@"category"];
Memo *m = [[Memo alloc] initWithTitle:title content:content category:category];
[self.memos addObject:m];
}
我的问题是:如何向plist(特别是我的plist中的Memo字典数组)添加新的Memo(三个字符串的字典)?您必须在NSDictionary中获取plist,然后将Memos数组读入NSMutableArray,向其中添加一个对象,然后将可变备忘录数组另存为字典中的备忘录,并将其写回plist文件。更改此行:
NSArray *tempArray = [tempDictionary objectForKey:@"memos"];
到
希望对你有帮助
并确保将self.memos数据写回文件
另请注意,您不能编辑捆绑包中的文件。在开始编辑和保存之前,您需要确保将其复制到文档目录。尝试以下操作:
[tempArray addObject:NewDictionary That you want to insert];
然后将此临时数组添加到临时字典
[tempDictionary setObject:tempArray forKey:@"memos"];
然后将tempdictionary保存到文件
[tempDictionary writeToFile:path atomically:YES];
希望能有帮助
[tempDictionary writeToFile:path atomically:YES];