我看到了几个示例,但在尝试保存我的文本字段输入并在重新启动应用程序时重新加载它时,我无法弄清楚出了什么问题。我的 .m 文件中有类似的内容(.h 文件只有一个<UITextViewDelegate>
);
@implementation C4WorkSpace{
UITextView *textField;
C4Button *okButton;
C4Label *savedText;
}
-(void)setup {
//add text field
CGRect textViewFrame = CGRectMake(20.0f, 20, self.canvas.width-40, 124.0f);
textField = [[UITextView alloc] initWithFrame:textViewFrame];
textField.returnKeyType = UIReturnKeyDone;
[textField becomeFirstResponder];
textField.delegate = self;
//textField.hidden=true;
[self.view addSubview:textField];
okButton=[C4Button buttonWithType:ROUNDEDRECT];
[okButton setTitle:@"Save" forState:NORMAL];
okButton.center=self.canvas.center;
[self.canvas addUIElement:okButton];
[okButton runMethod:@"saveDefault" target:self forEvent:TOUCHUPINSIDE];
savedText=[C4Label labelWithText:@"default"];
savedText.center=CGPointMake(self.canvas.center.x, self.canvas.center.y+40);
[self.canvas addLabel:savedText];
}
-(void)saveDefault{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:textField.text forKey:@"userName"];
[defaults synchronize];
C4Log(@"defaults: %@",defaults);
C4Log(@"defaults: %@", [defaults objectForKey:@"userName"]);
savedText.text=textField.text;
}
-(void)viewDidLoad{
NSMutableString *text=[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
C4Log(@"loadedText:%s", text);
textField.text=text;
savedText.text=text;
}
@end
我不确定到底出了什么问题,但是当我重新启动应用程序时,loadedText 总是:“¯8*:å”。不管我保存了什么。