setObject in a multidimensional dictionary
I have a 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</开发者_如何学Cstring>
</dict>
<key>3</key>
<dict>
<key>a</key>
<string>a3</string>
<key>b</key>
<string>b3</string>
</dict>
</dict>
</plist>
...which I init a mutable dictionary from (see below). I can reference a string easily with a nested method call:
NSLog(@"%@", [[plistItems objectForKey:@"1"] objectForKey:@"a"]);
Is there a way I can do a setObect on this particular key with a similar nested method, or do i have to do it the longer way as shown?
-(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
}
(memory management not included)
What about this:
[[plistItems objectForKey:@"1"] setObject:stringTemp forKey:@"a"];
When you initWithContentsOfFile
from your plist file, only the root dictionary is mutable. Sub-dictionaries are all immutable NSDictionary. So it would not be possible to write
[[plistItems objectForKey:@"1"] setObject:stringTemp forKey:@"a"];
To get a "full" mutable dictionary, you should use NSPropertyListSerialization
:
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:path];
NSError *error = nil;
NSPropertyListFormat format;
NSMutableDictionary *plistItems = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistData
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&error];
You will be able to change values like this:
[plistItems setValue:stringTemp forKeyPath:@"1.a"];
精彩评论