add dictionary to plist
I hope someone can help me with that I开发者_开发知识库 want to write a dictionary to a plist when i select a tableView row which already works but it only writes one entry. but every selection should be added.
my code so far:
NSString *plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"liste.plist"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[selectedEntry valueForKey:NAME], @"Name",
[selectedEntry valueForKey:add], @"Add"
, nil];
[tempArray writeToFile:plistPath atomically:YES];
I found a way to solve the problem. I initialize the Array in the viewDidLoad and filled it with the plist and now it works....
self.tempArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
and changed
[dictionary writeToFile:plistPath atomically:YES];
to
[tempArray writeToFile:plistPath atomically:YES];
I think that you should put all dictionaries into a mutable array which would be the root object of the plist. Otherwise you should come up with a solution to generate new keys for each entry added.
When you need to add stuff you just read up the mutable array from the plist, add to it, and save it. From what I recall, the methods are very similar between arrays and dictionaries when reading/writing plists.
Here is what I use:
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableDictionary *dict;
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
VALUE1, KEY1,
VALUE2, KEY2,
VALUE3, KEY3,
VALUE4, KEY4,
nil ];
NSString *err = nil;
NSData *plist;
plist = [NSPropertyListSerialization dataFromPropertyList:dict format:NSPropertyListBinaryFormat_v1_0 errorDescription:&err];
if([manager fileExistsAtPath:@"YourPlist.plist"] == NO){
[manager createFileAtPath:[NSString stringWithFormat:@"YourPlist.plist"] contents:plist attributes:nil];
}
[manager release];
If either object from selectedEntry is not a NSString, NSNumber, NSArray, NSDictionary, etc. then the write will not succeed:
From the NSDictionary reference document:
This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.
精彩评论