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!
In Objective-C, sending a message to
nil(anullreference 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 gridto 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
gridisnil.On a side note, you don’t need the extra
-retainfollowingalloc/init. Read the Memory Management Programming Guide for Cocoa. It will be your friend.