我有一个Settings.plist,我想在此文件中编辑一些值。
我的编辑/写作功能是:
- (void) setParamWithName: (NSString*) Name withValue: (NSString*) Value {
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Settings.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}
// checking if element exists, if yes overwriting
// if element not exists adding new element
[temp writeToFile:plistPath atomically:YES];
}
此函数读写(使用相同的值)Settings.plist。
我不知道(我对objective-c的了解还不够)如何添加新元素或编辑现有元素。任何人都可以帮助mi解决这个问题吗?
答案 0 :(得分:1)
我认为你想的更容易。
获得文件的路径后,将其读入NSDictionary。使用mutableCopy和NSMutableDictionary制作该字典的可变副本。 现在编辑可变字典(添加s.th.,删除s.th.,编辑s.th.等等)。
现在你已经完成了,你可以像使用temp一样把它写回旧路径。
你的主要问题是你没有使用该指令的可变版本。它会让你的生活更轻松。