iDevGames Forums
how to init and get a dictionary working - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Game Programming Fundamentals (/forum-7.html)
+--- Thread: how to init and get a dictionary working (/thread-4952.html)



how to init and get a dictionary working - kensuguro - Oct 2, 2005 09:53 AM

I'm having a hard time getting a working dictionary for some reason. I have a class that holds a lookup table, so if I do class(5), it'll throw me back say, "bongos". It can just be 2 arrays, but since I don't know how to use a dictionary, I'm doing this to learn.

In terms of syntax, I have a
Code:
    NSDictionary *codeList;
declaration in the .h file and a
Code:
NSDictionary *codeList = [NSDictionary dictionaryWithObjectsAndKeys:
    @"Cherry Coke",      [NSNumber numberWithInt:1],
    @"Pizza",            [NSNumber numberWithInt:2],
    @"Meat Balls",       [NSNumber numberWithInt:3],
    @"Wiener Schnitzel", [NSNumber numberWithInt:4], nil];
in the implementation. The implmentation is not a part of any method, it's just there.

The compiler returns a "initializer element is not constant" error message. I'm puzzled because the syntax seems right. Perhaps I need to put the initializing code as a class specific init? Or is it some other problem?

I got Cocoa with Objective C, Objective C Pocket Reference, and Cocoa Programming but they all pretty much zoom past the collections, so I'm frankly quite lost. Sometimes it's the basics that's the hardest because everyone assumes you know it already.


how to init and get a dictionary working - ThemsAllTook - Oct 2, 2005 11:02 AM

kensuguro Wrote:Perhaps I need to put the initializing code as a class specific init?

Precisely. Since your initialization involves method calls, rather than just assigning a constant value to the variable, it needs to be inside a function.

- Alex Diener


how to init and get a dictionary working - Fenris - Oct 2, 2005 11:44 AM

Just stick it in your -(id)init{} method Smile


how to init and get a dictionary working - kensuguro - Oct 2, 2005 02:05 PM

gotcha, I did the init thing right after I posted the question and was happy it worked, and also was the right answer. The whole dictionary thing now works. The program kinda sucks tho.. I input 1, and press a button, the program returns "apple". Way cool...

By the way, is there any way to reverse the lookup? Like, have the dictionary return Apple when I input 1, and also return 1 when I input Apple? (other than making double entries)


how to init and get a dictionary working - blobbo - Oct 2, 2005 02:33 PM

Sure - you'll have to iterate through your dictionary comparing each value against the input, though.

Use an NSEnumerator to iterate through your nsdictionary. It looks complicated, but it's actually quite simple. Apple's docs are good for this one.