2013-07-29 57 views
0

我有一个结构类似这样的plist中:如何在plist中将字典写入数组?

<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中的备忘录字典的数组)?

回答

0

您必须抓住NSDictionary中的plist,然后将Memos数组读取到NSMutableArray中,向其中添加一个对象,然后将可变的备忘录数组作为备忘录保存到字典中并将其写回到plist文件中。

0

改变这一行:

NSArray *tempArray = [tempDictionary objectForKey:@"memos"]; 

self.memos = [tempDictionary objectForKey:@"memos"]; 

希望它可以帮助...

,并确保你写回self.memos数据回文件。

另请注意,您无法编辑包中的文件。在开始编辑并保存之前,您需要确保将其复制到文档目录中。

0

试试这个:

[tempArray addObject:NewDictionary That you want to insert]; 

那么这个温度阵列添加到TempDictionary。

[tempDictionary setObject:tempArray forKey:@"memos"]; 

然后将tempdictionary保存到文件。

[tempDictionary writeToFile:path atomically:YES]; 

希望它有助于!