创建常量字典对象
我想完成类似这篇文章中正在做的事情: Constantants in Objective-C
但是,我想构造一个 NSDictionary。
我做类似的事情:
constants.hconstants.m
extern NSArray *const mFooKeys;
extern NSArray *const mFooObjects;
extern NSDictionary *const mFooDictionary;
如果
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];
我是否在dealloc中释放并且一切都很好,或者还有更多吗?这更像是一个谨慎的问题,而不是“出了什么问题”的问题,但我觉得我真的可能在没有意识到的情况下把事情搞砸。
I would like to accomplish something like what is being done in this post: Constants in Objective-C
however, i would like to construct an NSDictionary.
if i do something like:
constants.h
extern NSArray *const mFooKeys;
extern NSArray *const mFooObjects;
extern NSDictionary *const mFooDictionary;
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];
do i release in dealloc and everything is fine, or is there more to it? this is more a cautious question than a 'something is wrong' question, but i feel like i could really mess this up without realizing it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了拥有像
NSDictionary
这样基于其他核心数据类型的常量,您需要将其包含在将使用该常量的类中,或者创建一个 Singleton 类 并在那里存储NSDictionary
。只有一些类类型在您正在查看的实现中不起作用;您正在查找的常量代码需要用作对象才能正常工作,但我认为这违背了目的。我不清楚在简单常量实现中你能做什么和不能做什么的决定因素是什么,但我遇到了同样的问题,单例设计模式对我来说非常适合。 (无论哪种方式,您都应该适当地dealloc
,即使它们将在应用程序的生命周期中存在。)In order to have a constant like a
NSDictionary
that is based on other core data types, you either need to include it in the class that will be using the constant, or create a Singleton class and store theNSDictionary
there. There just some class types that will not work in the implementation you are looking at; the constants code you are looking would need to be used as an object in order to work correctly, but I think that kind of defeats the purpose. I'm not clear as what the determining factor is for what you can and can't do in the simple constants implementation, but I ran into the same issue and the Singleton design pattern worked perfectly for me. (Either way, you shoulddealloc
appropriately even though they will exist for the life of the application.)您将它们声明为常量,因此它们是在应用程序的整个生命周期中持续存在的单个对象。无需释放,因为在应用程序退出之前都需要它们。
您不想在 dealloc 中释放,因为每次释放相关类的实例时都会释放。
You're declaring these as constants, so they are single objects that will last for the lifetime of your application. No need to release, as they're needed until the application is quit.
You don't want to release in dealloc, as this will release every time an instance of the relevant class is deallocated.