How to use NSUserDefaults in a TableView?

Thursday, July 10, 2014

I would like to save data with NSUserDefaults. My app consists of a View Controller in which I have a TableView with UITextFields. The View Controller has a Save button at the top in Navigation Bar. The user could edit the UITextFields and then click on Save to save the data.

I would like to have your advices on how to do it. I started something like this : I declare an UITextFields in my .h file like this (just one data for example, but my App has 10 UITextfields) :

@property (weak, nonatomic) IBOutlet UITextField *email;

and then in my .m file I use a prepareForSegue to save the data when the user clicked on Save button :

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
if (sender != return;
NSString *userEmail = [ text];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:userEmail forKey:@"email"];
[defaults synchronize];
NSLog(@"Data saved");

I also retrieve my data in ViewDidLoad :

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userEmail = [defaults objectForKey:@"email"]; = userEmail;

In the .m file I have a cellForRowAtIndexPath to display the UITextfield.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if ([indexPath section] < 3) {
UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 8, 185, 30)];
playerTextField.adjustsFontSizeToFitWidth = YES;
playerTextField.textColor = [UIColor blackColor];

// First section
if ([indexPath section] == 0 && [indexPath row] == 0) {
playerTextField.placeholder = @"Smith";
playerTextField.keyboardType = UIKeyboardTypeDefault;
playerTextField.returnKeyType = UIReturnKeyDone;
if ([indexPath section] == 0 && [indexPath row] == 1) {
playerTextField.placeholder = @"John";
playerTextField.keyboardType = UIKeyboardTypeDefault;
playerTextField.returnKeyType = UIReturnKeyDone;

// Second section

playerTextField.delegate = self;
[playerTextField setEnabled: YES];

[cell.contentView addSubview:playerTextField];

return cell;

So my question is how to assign the first UITextfield to my email NSString ? Is that a correct way to proceed like this ?