I am creating a names generator app for iPhone and this is what I am trying to do.
- Allow the user to save the current generated name by clicking a save button.
In order to do this, here is what is happening:
- The current babyname is displayed in a
UILabel. - The user presses ‘save’ and then the label.text value is appended to a
NSMutableArray(I don’t think this is working in my code correctly). - The
NSMutableArrayis then saved inNSUserDefaults. - The contents will then be loaded in another view to populate
UITableViewcells.
My specific question is, am I handling this saving/persistent storage process correctly? Here is the snippet in question:
- (IBAction)saveName:(id)sender {
// save current baby name to array
NSMutableArray *babyNameArray = [[NSMutableArray alloc] init];
[babyNameArray addObject:babyname.text];
// save list of babynames to nsuserdefaults
[[NSUserDefaults standardUserDefaults] setObject:babyNameArray forKey:@"My Key"];
// for testing log names listed in nsuserdefaults
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
}
Here is a link to the pastebin of the whole file contents (with comments): http://pastebin.com/hQRM9Azh
Every time you add, you’re starting again with an empty array (
[[NSMutableArray alloc] init]) – instead of starting with the existing items.Here’s some code which adds to the existing entries instead: