如果委派了NSUserDefaults,则不会从UITextFields保存字符串

时间:2012-11-20 18:18:51

标签: uitextfield nsuserdefaults

源代码:

#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

问题是:action textFieldChanged不会影响“textField1”NSUserDefaults键来保存数据。如果我使用[[NSUserDefaults standardUserDefaults] setObject:textField1.text forKey:@“textField1”];在Summarize行动中,它运作良好。我的应用程序出了什么问题?

1 个答案:

答案 0 :(得分:0)

我认为您需要以下内容:

-(IBAction)textFieldChanged:(id)sender {
  [[NSUserDefaults standardUserDefaults] setObject: textField1.text forKey: @"textField1"];
  [[NSUserDefaults standardUserDefaults] setObject: textField2.text forKey: @"textField2"];
  [[NSUserDefaults standardUserDefaults] synchronize];  // THIS LINE
}