views:

760

answers:

3

Can anyone help me add children to a plist?

I think I want to record an index of rows from the plist and then state which index row to write the key too. I'm not sure how to say if the key will be a string, dictionary or array.

The following is code from another question on adding a key to root.

 NSString *path = @"path/to/some/file";
 NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
 [plist setObject:@"foo" forKey:@"aKey"];
 [plist writeToFile:path atomically:YES];
 [plist release];

Any help would be extremely appreciated :)

A: 

Note: I still need help but made progress.

The following code will add a plist array entry name "Hi" with children: Item 0, test1 Item 1, test2

NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:databasePath] mutableCopy];
NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
newArray = [NSArray arrayWithObjects:@"test1", @"test2", nil];
[plist setObject:newArray forKey:@"Hi"];
[plist writeToFile:databasePath atomically:YES];
[plist release];

I think making a dictionary item would work the same as the array item. I am still not sure how to add entires into children though :/

S-T-R-E-G-A
A: 

Here it is If you do everything as follows you can write out a plist. Dictionary -> array -> string Dictionary -> Dictionary -> Dictionary -> Array -> string etc...

Here's code that creates a "Row" Dictionary containing a "Hi" array containing 2 strings named Item 0 and Item 1 with names "test 1 and test 2.

NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:databasePath] mutableCopy];
NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
NSMutableDictionary *newDictionary = [[[NSMutableDictionary alloc] init] autorelease];
newArray = [NSArray arrayWithObjects:@"test1", @"test2", nil];
newDictionary = [NSDictionary dictionaryWithObject:newArray forKey:@"Hi"];
[plist setObject:newDictionary forKey:@"Row"];
[plist writeToFile:databasePath atomically:YES];
[plist release];

This is will crash if you try to write an item where 1 already exists. Anyone know how I cn give the string keys (i.e. Item 0, Item 1, etc...) a name?

S-T-R-E-G-A