简体   繁体   English

Xcode:为什么此代码无法使用NSUserDefaults保存UITextField?

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

I have an UITextField inside an UITableViewCell. 我在UITableViewCell中有一个UITextField。 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: 我尝试通过使用以下代码使UITextField调用动作:

    [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: 当我尝试通过单击“完成”以隐藏键盘来退出UITextField时,出现以下消息:

*** 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. 基本上,我认为在saveTextField方法中分配新字符串的前两行不是必需的。

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. 问题是我只创建了一个UITextfield,然后将其放入每个UITableViewCell中,这就是问题所在。 So I created individual UITextFields for every UITableViewCells and that fixed the problem :) 所以我为每个UITableViewCells创建了单独的UITextFields并解决了问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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