jump to navigation

Dictionary Dangers 9 July 2009

Posted by Oliver Mason in Apple, objective-c, programming.
trackback

I just spotted a bug that cost me several hours yesterday, without having a clue what was going on. I’m currently working on a program which indexes texts, and as I encounter words, I add them to a NSMutableDictionary with their positions in the text. All was working well, until I tested it on a bunch of texts, and it failed with some obscure message about key-value coding. I then added some NSLog messages, and discovered that the token it failed on was the at sign, @.

Today I had another look at the documentation of NSMutableDictionary, and especially the method valueForKey: where the problem seemed to occur. And there it was: “If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key.” Suddenly it dawned on me: I was using the wrong method. Instead of valueForKey: I should have used objectForKey: – the plain @-sign is discarded, and leaves an empty key (which did of course make the error message less comprehensible, as I couldn’t really tell it was empty).

Quick change in the code, and it works. Problem solved!

Lesson learned: always pay close attention to the available methods, and make sure it is the one you want, even if the one you’re using sounds like it’s the right one. And read the docs carefully!

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: