NSMutableDictionary 中没有保存键/值对

发布于 2024-08-23 00:57:58 字数 518 浏览 7 评论 0原文

当我的应用程序启动时,它会循环将带有网格上坐标键的随机数值添加到字典中。下面是一些代码:

[grid setObject:v forKey:k];

K 是一个“xy”形式的字符串,其中 x 和 y 是单位数整数,V 是 NSNumber。在添加之前,这两个内容都会记录到控制台,所以我知道这些不是问题。然而,尽管此代码运行了 49 次(对于 7 x 7 网格),字典最终还是空的。

grid 在我的头文件中定义为:

NSMutableDictionary *grid;

然后我在应用程序加载时初始化它(但我不知道是否必须这样做)使用代码:

grid = [[[NSMutableDictionary alloc] init] retain];

这真的让我感到困惑,因为我才刚刚开始学习 Objective- C 和我来自更加宽容的 C# 和 Python 世界。

预先感谢您的帮助!

When my app starts, it loops through adding values of random numbers with keys of co-ordinates on a grid to a dictionary. Here is a bit of the code:

[grid setObject:v forKey:k];

K is a string in form "xy" where x and y are single digit integers and V is an NSNumber. Both of these are logged to the console before adding so I know these aren't the problem. However, despite this code running 49 times (for a 7 x 7 grid) the dictionary is empty at the end.

grid is defined in my header file with:

NSMutableDictionary *grid;

And then I initialised it when the app loads (but I don't know if I have to do this) using the code:

grid = [[[NSMutableDictionary alloc] init] retain];

This is really confusing me because I have only just started learning Objective-C and I have come from the far more forgiving universe of C# and Python.

Thanks in advance for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

猫性小仙女 2024-08-30 00:57:58

在 Objective-C 中,向 nil(C# 世界中的 null 引用)发送消息既合法又常见。结果是nil,因此通常会悄无声息地过去。一旦您理解了这一点,就会发现它是一个非常有用的工具,可以使代码更加简洁(不检查 null 等)。因此,在向字典添加条目的行处放置一个断点。为此,请单击 Xcode 中该行旁边的装订线。打开断点运行您的应用程序。当调试器停在该行时,您可以将鼠标悬停在grid上。我怀疑您会看到它是nil (0x0)。您还可以打开运行控制台并输入po grid来打印gdb对grid的描述。我想你会再次发现它是零。

如果没有看到更多代码,就不可能帮助您找出为什么 gridnil

附带说明一下,您不需要在 alloc/init 之后添加额外的 -retain。阅读内存 Cocoa 管理编程指南 。它将成为你的朋友。

In Objective-C, sending a message to nil (a null reference in the C# world), is both legal and common. The result is nil, and so will often pass silently. Once you wrap your head around this, it's a very useful tool that makes code a lot cleaner (no checks for null, etc.). So, put a breakpoint at the line where you add an entry to the dictionary. To do so, click in the gutter next to the line in Xcode. Run your application with Breakpoints turned on. When the debugger stops at that line, you can hover the mouse over grid. I suspect you'll see that it's nil (0x0). You can also open the run console and type po grid to print gdb's description of grid. Again, I think you'll find that it's nil.

Without seeing more code, it will be impossible to help you track down why grid is nil.

On a side note, you don't need the extra -retain following alloc/init. Read the Memory Management Programming Guide for Cocoa. It will be your friend.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文