No key/value pairs being saved in NSMutableDictionary
When my app starts, it loops through adding values of random numbers with keys of 开发者_如何学Pythonco-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!
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.
精彩评论