gpt4 book ai didi

ios - 保存用户默认值 [iOS]

转载 作者:行者123 更新时间:2023-11-29 12:57:27 24 4
gpt4 key购买 nike

我看到了几个示例,但在尝试保存我的文本字段输入并在重新启动应用程序时重新加载它时,我无法弄清楚出了什么问题。我的 .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*:å”。我保存了什么并不重要。

最佳答案

我发现最简单的解决方案是设置


ViewDidLoad

text=[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];

并在设置

if (text!=nil) {
textField.text=text;
}

关于ios - 保存用户默认值 [iOS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20680725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com