创建一个常量字典对象

gri*_*eak 7 release constants objective-c nsdictionary

我想完成这篇文章中正在做的事情:Objective-C中的常量

但是,我想构建一个NSDictionary.

如果我这样做:

constants.h

extern NSArray *const mFooKeys;
extern NSArray *const mFooObjects;
extern NSDictionary *const mFooDictionary;
Run Code Online (Sandbox Code Playgroud)

constants.m

NSArray *const mFooKeys = [[NSArray alloc] initWithObjects: 
                                   @"Foo", @"Bar", @"Baz", nil];
NSArray *const mFooObjects = [[NSArray alloc] initWithObjects: 
                                   @"1", @"2", @"3", nil];
NSDictionary *const mFooDictionary = [[NSDictionary alloc] dictionaryWithObjects:mFooObjects 
                                                                         forKeys:mFooKeys]; 
Run Code Online (Sandbox Code Playgroud)

我是以dealloc发布的,一切都很好,还是有更多的东西?这个问题比一个"有问题"的问题更为谨慎,但我觉得如果没有意识到这一点,我真的可能会把它搞得一团糟.

Phi*_*gan 5

为了得到一个NSDictionary基于其他核心数据类型的常量,你需要将它包含在将使用常量的类中,或者创建一个Singleton类并存储NSDictionary它.只有一些类型在您正在查看的实现中不起作用; 您正在寻找的常量代码需要用作对象才能正常工作,但我认为这样做会使目的失败.我不清楚在简单的常量实现中你能做什么和不能做什么的决定因素,但我遇到了同样的问题,而且Singleton设计模式对我来说非常合适.(无论哪种方式,dealloc即使它们在应用程序的生命周期中存在,您也应该适当.)