再会!
我在 iOS 中执行嵌套属性列表时遇到问题。
因此,有两个UITextField
s 将接受随机值,然后将其保存到属性列表中。问题是,当我输入第二个值时,它会覆盖我的属性列表中的第一个值。
如何处理或编写嵌套属性列表?
这是我尝试的代码:
- (IBAction)writeToPlist:(id)sender
{
NSLog(@"Write.");
NSString *finalPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Data.plist"];
NSMutableDictionary *fruitDictionary = [[NSMutableDictionary alloc] init];
NSString *fruitName = [[NSString alloc] initWithString:[fruitNameField text]];
NSString *fruitDescription = [[NSString alloc] initWithString:[fruitDescriptionField text]];
NSDictionary *fruitDetail = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:fruitName, fruitDescription, nil]
forKeys:[NSArray arrayWithObjects:@"Fruit", @"Description", nil]];
NSMutableDictionary *fruitPlist = [[NSMutableDictionary alloc] initWithContentsOfFile:finalPath];
NSMutableArray *fruitArray = [fruitPlist objectForKey:fruitName];
if (fruitArray == nil) {
fruitArray = [[NSMutableArray alloc] init];
}
[fruitDictionary setObject:fruitDetail forKey:fruitName];
[fruitArray addObject:fruitDictionary];
[fruitArray writeToFile:finalPath atomically:YES];
[[self presentingViewController] dismissViewControllerAnimated:YES
completion:nil];
}
输出是:
<plist version="1.0">
<array>
<dict>
<key>Apple</key>
<dict>
<key>Description</key>
<string>Red</string>
<key>Fruit</key>
<string>Apple</string>
</dict>
</dict>
</array>
</plist>
我想要发生的是:
<plist version="1.0">
<array>
<dict>
<key>Apple</key>
<dict>
<key>Description</key>
<string>Red</string>
<key>Fruit</key>
<string>Apple</string>
</dict>
</dict>
<dict>
<key>Banana</key>
<dict>
<key>Description</key>
<string>Yellow</string>
<key>Fruit</key>
<string>Banana</string>
</dict>
</dict>
</array>
</plist>
顺便说一句,我的代码是否可以接受?我的意思是,有什么办法可以缩短它吗?