我想更改此属性列表中的值profileData.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>profiles</key>
<array>
<dict>
<key>Name</key>
<string>Default Profile</string>
<key>size</key>
<integer>0</integer>
</dict>
</array>
<key>settings</key>
<dict>
<key>length</key>
<string>cm</string>
</dict>
</dict>
</plist>
我想将键的整数设置size
为1
. 我已经这样做了:
// reading Property List as described in Property List Programming Guide
NSError *error = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"profileData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:@"profileData" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSMutableDictionary *temp = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListWithData:plistXML
options:NSPropertyListMutableContainersAndLeaves
format:&format
error:&error];
if (!temp) {
DNSLog(@"Error reading plist: %@, format: %ld", error, (long)format);
}
// getting the right dictionary
NSMutableArray *profiles = [temp objectForKey:@"profiles"];
NSMutableDictionary profile0 = [profiles objectAtIndex:0];
// Setting new integer
[profile0 setObject:[NSNumber numberWithInt:1] forKey:@"size"];
// saving objects in reverse
[profiles replaceObjectAtIndex:0 withObject:profile0];
[temp setObject:profiles forKey:@"profiles"];
// writing property list
[temp writeToFile:plistPath atomically:YES];
此代码有效。
我的问题:这是最好的方法吗?从磁盘读取属性列表是可以的。但是是否有必要将属性列表的所有“级别”保存在单独的可变对象中,然后将所有这些对象反向设置到属性列表的最高级别?
对我来说,以这种方式执行此操作似乎有点复杂,即使我想象一个具有更多级别的属性列表。如果可以以这种方式做到这一点,那就太好了:
[temp setObject:[NSNumber numberWithInt:1] forKeyPath:@"profiles.0.size"];