views:

41

answers:

2

I would like to accomplish something like what is being done in this post: http://stackoverflow.com/q/538996/252428

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.

A: 

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.

Chris Devereux
+1  A: 

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.)

Philip Regan