const static NSDictionary

I have to use this long dictionary of constants in my app. I decided to save on the CPU time and place it in its own class method as a static const variable, but for some reason it produces this error:
{quote}
error: initializer element is not constant
{quote}

+(const NSDictionary*)getNamesDictionary
{
const static NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:
@"value1",
//Very long list of values
nil] forKeys:[NSArray arrayWithObjects:
@"key1",
//Very long list of keys
nil]];
return dic;
}

Can someone suggest how to remedy this?

MacBook Pro 17", 2.66 GHz i7, 4GB 1067 DDR3 RAM, OS X 10.6.4 /// iPhone 4, 32GB, iOS 4

Posted on Jan 25, 2011 1:30 PM

Reply
6 replies

Jan 25, 2011 2:41 PM in response to Den B.

Hi Den -

static vars can't be initialized with code. Maybe you want something like this:
+ (NSDictionary*)getNamesDictionary {
static NSDictionary* dic = nil;

if (dic == nil)
dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:
@"value1",
//Very long list of values
nil] forKeys:[NSArray arrayWithObjects:
@"key1",
//Very long list of keys
nil]];
return dic;
}

- Ray

Jan 25, 2011 3:30 PM in response to Den B.

Ooops, sorry Den. I just pasted your initialization code without thinking 😟 We don't want to use the convenience method to create the dictionary without retaining it:

static NSDictionary* dic = nil;
+ (NSDictionary*)getNamesDictionary {

if (dic == nil)
dic = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:
@"value1",
//Very long list of values
nil] forKeys:[NSArray arrayWithObjects:
@"key1",
//Very long list of keys
nil]];
return dic;
}

As shown, you might also consider moving the static declaration out of the method so dic can be released in the dealloc method.

- Ray

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

const static NSDictionary

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.