Objective C - objectForKey 问题

发布于 2024-08-21 04:55:51 字数 482 浏览 3 评论 0原文

好的,我正在尝试为我的应用程序编写一个高分函数。

我的问题是,当尚未保存高分时,我的程序崩溃了。

如果我将其保存为:

[[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

禾厶谷欠 2024-08-28 04:55:51

initWithString 的 NSString 文档:说

参数

字符串

要从中复制字符的字符串。 该值不能为零。

objectForKey 的文档:说

返回值

与关联的对象
指定的键,或者如果键是nil
未找到。

问题似乎是,当您尝试检索尚不存在的firstName并尝试使用它作为输入创建一个NSString时,会返回nil

The NSString documentation for initWithString: says

Parameters

aString

The string from which to copy characters. This value must not be nil.

The documentation for objectForKey: says

Return Value

The object associated with the
specified key, or nil if the key was
not found.

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.

揪着可爱 2024-08-28 04:55:51

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.

唐婉 2024-08-28 04:55:51

您可以像这样加载“第一个”:

first = [[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"] retain];
if (!first) {
    // set default or do something else if there wasn't a value saved
    first = @"N/A";
}

You could load "first" like this:

first = [[[NSUserDefaults standardUserDefaults] objectForKey:@"firstName"] retain];
if (!first) {
    // set default or do something else if there wasn't a value saved
    first = @"N/A";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文