I saw a couple of examples but I cannot figure out what's going wrong when trying to save my text field input and reload it when restarting the app.
I have something like this in my .m file (.h file only has a <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
I'm not sure what exactly is going wrong, but when I restart the app the loadedText is always: "¯8*:å". Doesn't matter what I saved.
I found the easiest solution is to set in
ViewDidLoad
and in setup