简体   繁体   English

如何设置用于NSDictionary的键值对?

[英]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: 这就是我在m文件中使用的内容,例如:

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

How do i set up the pre-determined names for the dictionary keys? 如何设置字典键的预定名称?

Usually Apple leaves a bunch of constants defined in the header, like for example in the NSAttributedString Application Kit Additions : 通常,Apple会在标头中保留一堆常量,例如在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 * NSFontAttributeName;
NSString *NSParagraphStyleAttributeName; NSString * NSParagraphStyleAttributeName;
[...] [...]

My suggest is to use your own constants if the attributes are way too many (with define or using global const variables). 我的建议是,如果属性太多(使用define或使用全局const变量),则使用自己的常量。

For example in the .m file (where CN is the company name): 例如在.m文件中(其中CN是公司名称):

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. 或者您也可以使用define。

You may also make things easier for the user, making a method that return a NSArray or NSSet containing the list of all variables. 您还可以使方法更简单,使用户返回包含所有变量列表的NSArrayNSSet

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. 如果相反,您只需要保留少数几个属性,则重新考虑使用字典的选择,并使用包含所有属性的类(可通过KVC访问)。

You can just put #define statements in your .m file: 您可以将#define语句放入.m文件中:

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

etc. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM