Database Reference
In-Depth Information
-(void)updateDefaultForTextField:(UITextField *)textField {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if([textField isEqual:_txtDisplayName]){
if(![[userDefaults stringForKey:CTDisplayName] isEqualToString:textField.text]){
[userDefaults setObject:textField.text forKey:CTDisplayName];
[userDefaults synchronize];
}
} else {
if(![[userDefaults stringForKey:CTFavoriteNumber] isEqualToString:textField.text]){
[userDefaults setObject:[NSNumber numberWithFloat:[textField.text floatValue]]
forKey:CTFavoriteNumber];
[userDefaults synchronize];
}
}
}
We start off by grabbing the reference to our
NSUserDefaults
object. We then add an if statement to
check whether we are working with
_txtDisplayName
textfield or
_txtFavoriteNumber
. We use this to
determine which key we should be working with. Then we check the current text field value against
the
userDefaults
value to determine whether a change has in fact been made. If a change was
made, we set the new value in
userDefaults
and call
synchronize
. The
synchronize
method is what
forces the save to take place in
NSUserDefaults
; otherwise the OS invokes this method automatically
at periodic intervals.
Next we adopt the
UITextFieldDelegate
protocol. Adopting this protocol tells the compiler that
we intend to act as the delegate for a
UITextField
and that we will implement all required delegate
methods as well as any optional methods. If your class does not completely conform to the protocol,
the compiler will give you warnings letting you know. Select the
SettingsViewController.h
file and
change the interface definition to this:
@interface SettingsViewController : UITableViewController <UITextFieldDelegate>
In the
SettingsViewController.m
file we need to add one optional
UITextFieldDelegate
method.
The method we implement is
textFieldShouldReturn:
. This method is called when the user presses
Return on the keyboard. We use this method to change the first responder. In our case the first
responder is the object that will be responding to the keyboard. We will also add a pragma mark
above this method so that we can easily find it in the jump bar.
#pragma mark - UITextFieldDelegate Methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self updateDefaultForTextField:textField];
if([textField isEqual:_txtDisplayName])
[_txtFavoriteNumber becomeFirstResponder];
else
[_txtFavoriteNumber resignFirstResponder];
return YES;
}
Search WWH ::
Custom Search