Pripyat
Pripyat

Reputation: 2937

NSMutableArray Problem - iPhone

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?

Upvotes: 0

Views: 352

Answers (1)

Rob Napier
Rob Napier

Reputation: 299663

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.

Upvotes: 2

Related Questions