我有一个plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>1</key>
<dict>
<key>a</key>
<string>a1</string>
<key>b</key>
<string>b1</string>
</dict>
<key>2</key>
<dict>
<key>a</key>
<string>a2</string>
<key>b</key>
<string>b2</string>
</dict>
<key>3</key>
<dict>
<key>a</key>
<string>a3</string>
<key>b</key>
<string>b3</string>
</dict>
</dict>
</plist>
...我从中创建了一个可变字典(见下文)。我可以使用嵌套方法调用轻松引用字符串:
NSLog(@"%@", [[plistItems objectForKey:@"1"] objectForKey:@"a"]);
我是否有办法使用类似的嵌套方法对此特定键执行setObect,或者我必须按照显示的更长的方式执行此操作?
-(void) writeOneItemInADictionary
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"Plist3" ofType:@"plist"];
NSMutableDictionary *plistItems = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
//This will return an object for a specific key:
//NSLog(@"%@", [[plistItems objectForKey:@"1"] objectForKey:@"a"]);
NSString *stringTemp = [[NSString alloc] initWithString: @"a1 modified"];
//I want to do something similar with setObject,to modify a1:
//[[plistItems setObject:stringTemp forKey:@"1"]forKey:@"a"]]; //not correct - does not work
//Or do I have to do it this longer way?:
NSMutableDictionary *plistSubItems = [[NSMutableDictionary alloc] init];
plistSubItems = [plistItems objectForKey:@"1"];
[plistSubItems setObject:stringTemp forKey:@"a"];
NSLog(@"plistSubItems: %@", plistSubItems);
NSLog(@"plistItems %@", plistItems); //longer way works fine
}
(不包括内存管理)
答案 0 :(得分:1)
这个怎么样:
[[plistItems objectForKey:@"1"] setObject:stringTemp forKey:@"a"];
答案 1 :(得分:0)
当您从plist文件中initWithContentsOfFile
时,只有根字典是可变的。子词典都是不可变的NSDictionary。所以不可能写
[[plistItems objectForKey:@"1"] setObject:stringTemp forKey:@"a"];
要获得“完整”可变字典,您应该使用NSPropertyListSerialization
:
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:path];
NSError *error = nil;
NSPropertyListFormat format;
NSMutableDictionary *plistItems = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistData
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&error];
您可以更改以下值:
[plistItems setValue:stringTemp forKeyPath:@"1.a"];