NSMutableDictionary 中没有保存键/值对
当我的应用程序启动时,它会循环将带有网格上坐标键的随机数值添加到字典中。下面是一些代码:
[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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Objective-C 中,向
nil
(C# 世界中的null
引用)发送消息既合法又常见。结果是nil
,因此通常会悄无声息地过去。一旦您理解了这一点,就会发现它是一个非常有用的工具,可以使代码更加简洁(不检查 null 等)。因此,在向字典添加条目的行处放置一个断点。为此,请单击 Xcode 中该行旁边的装订线。打开断点运行您的应用程序。当调试器停在该行时,您可以将鼠标悬停在grid
上。我怀疑您会看到它是nil
(0x0
)。您还可以打开运行控制台并输入po grid
来打印gdb对grid
的描述。我想你会再次发现它是零。如果没有看到更多代码,就不可能帮助您找出为什么
grid
为nil
。附带说明一下,您不需要在
alloc/init
之后添加额外的-retain
。阅读内存 Cocoa 管理编程指南 。它将成为你的朋友。In Objective-C, sending a message to
nil
(anull
reference in the C# world), is both legal and common. The result isnil
, 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 overgrid
. I suspect you'll see that it'snil
(0x0
). You can also open the run console and typepo grid
to print gdb's description ofgrid
. 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
isnil
.On a side note, you don't need the extra
-retain
followingalloc/init
. Read the Memory Management Programming Guide for Cocoa. It will be your friend.