使用 NSUserDefaults 保存和检索 UILabel 值
我尝试将 UILabel 值保存到 NSUserDefaults 中。我使用以下代码执行了 IBAction
:
-(IBAction)saveData:(id)sender {
NSString *resultString = label.text;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:resultString forKey:@"result"];
[prefs synchronize];
}
然后,我使用 Touch Up Inside
将其连接到按钮。 按下按钮后日志显示的内容:
result = 0;
当我第二次按下时,它就起作用了。
result = "28.34";
我做错了什么以及如何检索结果?
编辑
使用此代码,我在日志中显示结果。我把它放在同样的动作上。
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
I trying to save UILabel
value to NSUserDefaults
. I did IBAction
with this code:
-(IBAction)saveData:(id)sender {
NSString *resultString = label.text;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:resultString forKey:@"result"];
[prefs synchronize];
}
Then, I connect it to button with Touch Up Inside
.
What log shows after I pressed the button:
result = 0;
When I pressed a second time, then it works.
result = "28.34";
What I'm doing wrong and how can I retrieve a result?
EDIT
With this code I display result in log. I put it to same action.
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码看起来正确,因此问题可能不是您发布的函数,而是包含您的
NSLog
的代码。您可能会以错过第一次设置值的方式记录该值。Your code looks correct, so the issue is probably not the function you posted but rather the code that contains your
NSLog
. You might be logging the value in a way that misses the first time it gets set.你的日志语句应该是
这应该是在 NSUserDefaults 中设置对象之后。
Your log statement should be
This should be after you set the object in NSUserDefaults.
将其添加到 appDelegate 中的 applicationDidFinishLaunching 或 viewController 的 init 方法中(您必须创建一个):
Add this to your applicationDidFinishLaunching in appDelegate or in init method in viewController(you have to create one) :