繁体   English   中英

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

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

我想通过带有预定义键集的多个方法传递字典。 我已经在以前使用的类中看到了这一点,但是不确定如何设置。 这就是我在m文件中使用的内容,例如:

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

如何设置字典键的预定名称?

通常,Apple会在标头中保留一堆常量,例如在NSAttributedString Application Kit Additions中

标准属性

属性字符串支持以下文本标准属性。 如果密钥不在词典中,请使用下面描述的默认值。

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

我的建议是,如果属性太多(使用define或使用全局const变量),则使用自己的常量。

例如在.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";

并在头文件中:

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;

或者您也可以使用define。

您还可以使方法更简单,使用户返回包含所有变量列表的NSArrayNSSet

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

您可以将#define语句放入.m文件中:

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

等等

暂无
暂无

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

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