ソースコード:
#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"]; を使用する場合 要約アクション内では、正常に機能します。アプリの何が問題になっていますか?