Andrew
Andrew

Reputation: 16051

How do I set up key-value pairs for use with NSDictionary?

I want to pass a dictionary around multiple methods, with a pre-defined key set. I've seen this done in classes I've used before, but am unsure how to set this up. This is what i'd use in the m file, for example:

NSString *name = [dictionary objectForKey:kObjectsName];
NSDate *date = [dictionary objectForKey:kObjectsDate];

How do i set up the pre-determined names for the dictionary keys?

Upvotes: 0

Views: 310

Answers (2)

rdelmar
rdelmar

Reputation: 104092

You can just put #define statements in your .m file:

#define kObjectsName @"myName"
#define kObjectsDate @"myDate"

etc.

Upvotes: 1

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

Usually Apple leaves a bunch of constants defined in the header, like for example in the NSAttributedString Application Kit Additions:

Standard Attributes

Attributed strings support the following standard attributes for text. If the key is not in the dictionary, then use the default values described below.

NSString *NSFontAttributeName;
NSString *NSParagraphStyleAttributeName;
[...]

My suggest is to use your own constants if the attributes are way too many (with define or using global const variables).

For example in the .m file (where CN is the company name):

NSString* const CNURLKey= @"URLKey";
NSString* const CNupdateTimeKey= @"updateTimeKey";
NSString* const CNtagsKey= @"tagsKey";
NSString* const CNapplicationWillTerminateKey= @"applicationWillTerminateKey";
NSString* const CNtagAddedkey= @"tagAddedkey";
NSString* const CNtagRemovedKey= @"tagRemovedKey";
NSString* const CNcolorKey= @"colorKey";

And in the header file:

extern NSString* const CNURLKey;
extern NSString* const CNupdateTimeKey;
extern NSString* const CNtagsKey;
extern NSString* const CNapplicationWillTerminateKey;
extern NSString* const CNtagAddedkey;
extern NSString* const CNtagRemovedKey;
extern NSString* const CNcolorKey;

Or you may also use define as well.

You may also make things easier for the user, making a method that return a NSArray or NSSet containing the list of all variables.

If instead you need to hold just few attributes, reconsider the choice of using a dictionary, and use a class that contains all the attributes, accessible through KVC.

Upvotes: 3

Related Questions