Accessing Primitives From NSDictionarys in Cocoa…


This post was originally published in 2009
It may contain stale & outdated information. Or it may have grown more awesome with age, like the author.

This “gotcha” had me scratching my head for a little while.

Edit: this “gotcha” stemmed more from my inexperience with Cocoa than anything else. NSDictionaries store only objects, one shouldn’t try to insert int/float/bool etc into one. Instead use NSNumber for these values. Duh.

When storing various NSObjects in an NSMutableDictionary, I assumed one would access (in this case the object being stored is an NSColor) them like:

[[dictionary objectForKey:idle_TabBorderAllColourKey] color]

I also assumed that one would access “int”, “float” and other primitives like:

[dictionary objectForKey:idle_TabBorderAllWidthKey]

After writing, compiling and attempting run my code, however, I discovered that I was wrong.

It should be done like so:

[dictionary objectForKey:idle_TabBorderAllColourKey]

For NSObjects, and:

[[dictionary objectForKey:idle_TabBorderAllWidthKey] intValue]

for primitives.

Cocoa noob learns more about Cocoa with each passing minute!

Comments (2) | Trackback