Objective C - objectForKey 问题
好的,我正在尝试为我的应用程序编写一个高分函数。
我的问题是,当尚未保存高分时,我的程序崩溃了。
如果我将其保存为:
[[NSUserDefaults standardUserDefaults] setObject:@"[given string]" forKey:@"firstName"];
首先,它工作正常。但是,如果我第一次启动程序并尝试使用以下代码查看高分:
first = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"]];
就会发生不好的事情。
基本上,是否可以查看firstName 下是否尚不存在任何内容?有没有一种方法可以在不删除任何可能已经存在的名称的情况下进行初始化?
谢谢。
Okay, I'm trying to write a high score function for my app.
My problem is that when no high score has been saved yet, my program crashes.
If I save it with:
[[NSUserDefaults standardUserDefaults] setObject:@"[given string]" forKey:@"firstName"];
first, it works fine. However, if I start up the program for the first time and try to view the high scores with the following code:
first = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"]];
bad things happen.
Basically, is there away to see if nothing yet exist under firstName? Is there a way to initialize without erasing any name that might already be present?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
initWithString 的 NSString 文档:说
objectForKey 的文档:说
问题似乎是,当您尝试检索尚不存在的firstName并尝试使用它作为输入创建一个NSString时,会返回nil
The NSString documentation for initWithString: says
The documentation for objectForKey: says
The problem seems to be that there is a nil returned when you try to retrieve firstName that doesn't exist yet and try to create a NSString with it as input.
NSUserDefaults 实例方法
registerDefaults:
正是用于此目的:您可以为您的首选项设置默认值,这些值将被为该设置设置的任何其他值覆盖。相同的偏好键。只需确保尽早调用它,以便它将在任何需要访问您的首选项的代码之前运行。The NSUserDefaults instance method
registerDefaults:
is meant for exactly this purpose: You can set default values for your preferences that will be overridden by any other value set for the same preference key. Just make sure to call it early enough that it will run before any code that needs to access your preferences.您可以像这样加载“第一个”:
You could load "first" like this: