Reputation: 1291
I save value that user have been entered using NSUserDefaults. All works fine and data saves and retrieves. But how can I set a default value for that UITextField? When I use
- (void)viewDidLoad
{
textField.text = @"12345";
}
or put Text in nib file doesn't work, app start with empty field.
- (IBAction) saveBtnPresssed : (id) sender
{
myString1 = [[NSString alloc] initWithFormat:textField.text];
[textField setText:myString1];
NSUserDefaults *stringDefault = [NSUserDefaults standardUserDefaults];
[stringDefault setObject:myString1 forKey:@"stringKey"];
NSLog(@"%@",myString1);
}
Upvotes: 1
Views: 6951
Reputation: 1762
Double click on UITextField
in your storyboard and write your default value.
This works in Xcode 5.1!
Upvotes: 1
Reputation: 7185
I wouldn't set the values yourself, XCode provides a far easier way of doing this using bindings.
The way in which this works, would be you'd set your textfield a binding, and give it a name so that it can be identified, such as 'intialTextField'. The value is then automatically stored in NSUserDefaults, and updated on application close.
In XCode, click on the textField you want to bind, then open the Inspector. Then click the Tab second from the right. This is the 'bindings' tab.
Click the drop-down arrow on the 'Value' field and check the 'Bind to User Defaults...'
In the 'Model key path', set the name you want to identify your textfield with, this can be anything you want.
Then, whenever you enter something in your TextField, it will be saved on application exit. If you need this value to be saved straight away (only in rare cases is this necessary), you can enter the following code in your application:
[yourTextField synchronize];
On application startup you can then use NSUserDefaults to re-set the value of the textfield with the identifier you set earlier.
Hope this helps!
Upvotes: 4