Home > Uncategorized > Choosing NSDictionary Keys

Choosing NSDictionary Keys

February 28, 2015

Say you’re creating a dictionary in Objective-C. The idea is that you have two objects that you want to link, where whenever you reference the one (a key), you get in return the other (the value). For example, you’re car shopping, and you’re writing a little app to help you pick which car you want. So you create some Car objects, and then go about classifying them. You pick some criteria, like “fastest car” and “most cup holders”, and you want each to reference the appropriate car. And you want all of these together, in one place, so that you can pass this dictionary around and make some kind of checks. 

What do you use as the keys for this? NSDictionary has some pretty strict requirements as to what object can be a key, so most of the time the easiest option is an NSString. I guess you can just create some string literals, and use something like @fastestCar and @mostCupHolders. But that just looks… messy. You could initialize a string like NSString *fastestCar = [NSString stringWithString:@“fastestCar”] , but again, that seems like overkill. It would be nice if you could use an enum, but NSDictionary requires an object.

I noticed that for Apple’s use of imagePickerController, you’re passed a dictionary when the user choses photo. That dictionary contains the image itself, as well as some metadata. What was interesting to me was the keys seem were clearly objects, but really the type was arbitrary. All we were concerned with were the names, which were characteristically descriptive (e.g. UIImagePickerControllerOriginalImage). 

Looking at the declaration, it appears that it’s defined as an NSString * const. Is there a string built in there? Not as far as I can tell. And it wouldn’t matter if there was. 

The object, I learned cannot be nil, but it doesn’t have to actually be some arbitrary string either. Simply declaring NSString *const fastestCar = [[NSString alloc] init]; is enough. You’ve got an initialized NSString that makes a valid key.

Why bother? It’s not going to make a huge difference to your code’s readability, but it can lessens the cognitive burden of having to figure out a placeholder string, and it just looks cleaner than throwing string literals in there every time you want to access a value. It’s boilerplate, but it can be worth it if you’re going to be reusing this key more than a handful of times.  

Advertisement
Categories: Uncategorized Tags:
%d bloggers like this: