Creating a constant dictionary object

若如初见. 提交于 2019-12-19 17:38:08

问题


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.


回答1:


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 the NSDictionary 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 should dealloc appropriately even though they will exist for the life of the application.)




回答2:


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.



来源:https://stackoverflow.com/questions/3855556/creating-a-constant-dictionary-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!