源代码:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property IBOutlet UILabel *label;
@property IBOutlet UITextField *textField1;
@property IBOutlet UITextField *textField2;
@property NSInteger textFieldInt1, textFieldInt2;
@property NSString *textFieldStr1, *textFieldStr2;
-(IBAction)Summarize:(id)sender;
-(IBAction)textFieldChanged:(id)sender;
-(void)loadLastActions;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize label, textField1, textField2, textFieldInt1, textFieldInt2, textFieldStr1, textFieldStr2;
-(IBAction)Summarize:(id)sender {
textFieldInt1=[textField1.text integerValue];
textFieldInt2=[textField2.text integerValue];
label.text=[NSString stringWithFormat: @"%d", textFieldInt1+textFieldInt2];
[self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
//Do whatever you need to to save etc...
[textField resignFirstResponder];
return NO;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(![string intValue] && ![string isEqualToString:@""] && ![string isEqualToString:@"0"])
{
return NO;
} else {
return YES;
}
}
-(IBAction)textFieldChanged:(id)sender {
[[NSUserDefaults standardUserDefaults] setObject: textField1.text forKey: @"textField1"];
[[NSUserDefaults standardUserDefaults] setObject: textField2.text forKey: @"textField2"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
- (void)loadLastActions
{
if ([[NSUserDefaults standardUserDefaults] objectForKey: @"textField1"] != nil)
{
textField1.text = [[NSUserDefaults standardUserDefaults] stringForKey: @"textField1"];
}
if ([[NSUserDefaults standardUserDefaults] objectForKey: @"textField2"] != nil)
{
textField2.text = [[NSUserDefaults standardUserDefaults] stringForKey: @"textField2"];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.textField1 setReturnKeyType:UIReturnKeyDone];
[self.textField2 setReturnKeyType:UIReturnKeyDone];
[self loadLastActions];
}
@end
问题是:操作 textFieldChanged 不会影响“textField1” NSUserDefaults 键来保存数据。如果我使用 [[NSUserDefaults standardUserDefaults] setObject: textField1.text forKey: @"textField1"]; 在 Summarize 操作中,它工作正常。我的应用程序有什么问题?