简体   繁体   中英

Xcode: Why doesn't this code work for saving UITextField using NSUserDefaults?

I have an UITextField inside an UITableViewCell. What I want't is for the app to save the text the user inputs. I've tried by making the UITextField call a action with this code:

    [TextField addTarget:self action:@selector(saveTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];

However this action that it load doesn't work correctly:

- (IBAction)saveTextField:(id)sender {

NSString *TextFieldString = [[NSString alloc] initWithString:TextField.text];
[TextField setText:TextFieldString];
NSUserDefaults *UserSettings = [NSUserDefaults standardUserDefaults];
[UserSettings setObject:TextField forKey:@"TextField"];    }

When I exit the UITextField by trying to hide the keyboard by clicking "Done" I get this message:

*** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSInvalidArgumentException> *** -[NSPlaceholderString initWithString:]: nil argument

and nothing happens in the app.

Any thoughts?

Thanks in advance :)

I use the exact same functionality in one of my apps, and this is the code I use:

[[NSUserDefaults standardUserDefaults]setObject: textField.text forKey:@"TextField"];

Basically, I don't think the first two lines in your saveTextField method where you alloc a new string are necessary.

To begin with: thanks for your effort and time :)

Turns out the problem wasn't with the code that saves and loads it. The problem was that I only created one UITextfield which I then put into every UITableViewCell and that was the problem. So I created individual UITextFields for every UITableViewCells and that fixed the problem :)

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