PDA

View Full Version : An Array Of Dictionaries Not Writing To File Correctly?




Darkroom
Aug 29, 2009, 07:33 AM
not sure what is my error. i'm attempting to create a .plist that is an array of dictionaries. only the root (array) of the .plist is being created, while the dictionary object is missing.


- (NSString *)measurementsDataPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}

- (void)viewWillAppear:(BOOL)animated
{
NSMutableDictionary *dictionaryItem = [[NSMutableDictionary alloc] init];
[dictionaryItem setObject:[NSString stringWithFormat:@"Name String Test"] forKey:@"name"];
[dictionaryItem setObject:[NSString stringWithFormat:@"Measurements String Test"] forKey:@"measurement"];
[self.measurementsDataArray addObject:dictionaryItem];
[self.measurementsDataArray writeToFile:[self measurementsDataPath] atomically:YES];
...


self.measurementsDataArray is an NSMutableArray object.



kainjow
Aug 29, 2009, 08:17 AM
If you NSLog() your array before you write it to file, does it show everything correctly?

Darkroom
Aug 29, 2009, 09:58 AM
If you NSLog() your array before you write it to file, does it show everything correctly?

it does not.


NSMutableDictionary *dictionaryItem = [[NSMutableDictionary alloc] init];
[dictionaryItem setObject:[NSString stringWithFormat:@"Name String Test"] forKey:@"name"];
[dictionaryItem setObject:[NSString stringWithFormat:@"Measurements String Test"] forKey:@"measurement"];
[measurementsDataArray addObject:dictionaryItem];
NSLog(@"%@", measurementsDataArray);


NSLog returns (null)
:confused:

kainjow
Aug 29, 2009, 10:05 AM
Can you post the code that initializes the array?

Darkroom
Aug 29, 2009, 10:12 AM
the array is declared in the header and synthesized. is this error happening because of that?

kainjow
Aug 29, 2009, 10:18 AM
When you synthesize an object you're only creating the accessor methods to access that object. You still need to initialize the object like any other.

Darkroom
Aug 29, 2009, 10:22 AM
ah of course. silly me. the following works:


NSMutableDictionary *dictionaryItem = [[NSMutableDictionary alloc] init];
[dictionaryItem setObject:[NSString stringWithFormat:@"Name String Test"] forKey:@"name"];
[dictionaryItem setObject:[NSString stringWithFormat:@"Measurements String Test"] forKey:@"measurement"];
measurementsDataArray = [[NSMutableArray alloc] init];
[measurementsDataArray addObject:dictionaryItem];
[dictionaryItem release];
[measurementsDataArray writeToFile:[self measurementsDataPath] atomically:YES];