views:

99

answers:

1

Hi,

I'm trying to get a UITableView to read it's data from a file. I've attempted it like this:

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullFileName = [NSString stringWithFormat:@"%@/entries.plist", documentsDirectory];

self.dataForTable = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];

This compiles fine, but when saving something to the file in the following snippet, the file is not saved nor anything is written to the array:

NSMutableDictionary*userDictionary;
userDictionary = [[NSMutableDictionary alloc] init];
[userDictionary setObject:name.text forKey:@"name"];
[userDictionary setObject:email.text forKey:@"email"];
[userDictionary setObject:serial.text forKey:@"serial"];
[userDictionary setObject:notes.text forKey:@"notes"];
[userDictionary setObject:[NSNumber numberWithInt:[licenseType selectedRowInComponent:0]] forKey:@"license_type"];
[userDictionary setObject:[date date] forKey:@"date"];
[userDictionary setObject:[NSNumber numberWithBool:[paymentSwitch isOn]] forKey:@"payment"];

NSString*dirToSaveTo = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

NSString*fileName = [NSString stringWithFormat:@"%@.plist",name.text];

NSString*saveName = [dirToSaveTo stringByAppendingPathComponent:fileName];

[userDictionary writeToFile:saveName atomically:NO];

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullFileName = [NSString stringWithFormat:@"%@/entries.plist", documentsDirectory];

[self.dataForTable addObject:name.text];

NSLog(@"%@",self.dataForTable);

[self.dataForTable writeToFile:fullFileName atomically:YES];

The NSLog just returns (null). The *plist file is never written. What am I doing wrong?

+2  A: 

Almost certainly this line is failing, and you're not checking whether it returned nil:

self.dataForTable = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];

Once it does return nil, every other call to it does nothing. The most likely problems are that the file path you have constructed is incorrect and doesn't point to the file, or that the file is not a proper plist.

Rob Napier
it doesn't exist on first run, but it should get created by the second snippet if you see what I mean? Or do I understand this wrong? the way i see it is so: It points to nil creating an empty NSArray - > I add an object in my second snippet so my array has one object, then save it so it is available on the next run. am i thinking wrong here?
David Schiefer
`nil` is not an empty array. If you want an empty array, use `[NSArray array]`, or `[[NSArray alloc] init]`, or something else that will actually do what you're expecting!
Wevah
thanks you are right - how could i've missed that. :)
David Schiefer