【问题标题】:How do I set up key-value pairs for use with NSDictionary?如何设置键值对以与 NSDictionary 一起使用?
【发布时间】:2013-01-08 02:06:11
【问题描述】:

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

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

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

【问题讨论】:

  • kObjectsName 和 kObjectsDate 是一些字符串,您将它们传递给获取对象。请详细说明How do i set up the pre-determined names for the dictionary keys?
  • 你想要什么..设置值或获取值
  • 所以在我上面发布的代码中,这就是我将在方法内部使用的内容。我想知道怎么可能做到这一点。在 .h 文件中设置这些默认名称的标准方法是什么?
  • 公司名称加上变量名称,例如 CNObjectsDate。

标签: iphone objective-c ios nsdictionary key-value


【解决方案1】:

Apple 通常会在标头中定义一堆常量,例如在 NSAttributedString Application Kit Additions 中:

标准属性

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

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

如果属性太多(使用定义或使用全局 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 访问。

【讨论】:

  • 我使用FOUNDATION_EXPORT,我认为它优于extern
  • @noa 对于 Objective-C,FOUNDATION_EXPORT 宏的结果是“extern”。
【解决方案2】:

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

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

等等

【讨论】:

  • 使用NSString * const 可避免在跨多个.m 文件使用时分配字符串的另一个副本。
猜你喜欢
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 2012-08-06
相关资源
最近更新 更多