简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM