我如何设置键值对用于NSDictionary



我想在多个方法之间传递一个字典,并使用预定义的键集。我在以前使用过的课程中看到过这样做,但不确定如何设置它。这就是我在m文件中使用的内容,例如:

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

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

通常Apple会在header中留下一堆常量定义,例如在NSAttributedString Application Kit Additions中:

标准属性

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

NSString *NSFontAttributeName;
[…]

我的建议是,如果属性太多,使用你自己的常量(与定义或使用全局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"

等。

最新更新