iPhone inputting NSUserDefaults into a UITextField

2019-03-01 08:45发布

问题:

I am writing a program where I where the first time a user runs it - they will have to fill out about 10 different UITextFields. I am trying to save the fields so that on subsequent runs of the program that whatever they previously put will already be displayed in those UITextFields so the wont have to re-input it in - unless they want to edit something in which case they still have that option. I think that I have figured out a good way to save the strings using NSUserDefaults but now I am trying to figure out how to have those fields populate a UITextField - it doesnt seem as easy as if they were UILabels. This is the route I am attempting:

// in the viewDidLoad portion.
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults]; //Hooks.
NSString *placeHolderName = [userData stringForKey:@"name"];

txtName.text = @"%@", placeHolderName;

When I do this, it simply displays the '%@' in the textfields. I want whatever variable being held by placeHolderName to be automatically put into that UITextField. Is this possible?

回答1:

Just use:

txtName.text = placeHolderName;

or

txtName.text = [NSString stringWithFormat:@"%@", placeHolderName];

In code you have now you accidentally use Comma operator that evaluates its first expression (txtName.text = @"%@"), discards the result and returns the 2nd (placeHolderName)



回答2:

If I try to set a text of a UITextField in viewDidLoad, the UITextField is always nil, thus nothing happens. When should the

txtName.text = placeHolderName 

be called, if I need to populate the text field with the default value when the UIViewController loads?