Constant NSDictionary / NSArray for class methods

I am trying to encode a global sort table.

I have game data that is stored in character / string format in plist, but which should be in integer / id format when loading.

For example, in a level data file, β€œp” means player. In the game code, the player is represented as an integer 1. This allows me to perform some bitwise operations, etc. I am very simplifying here, but trying to find the point. In addition, there is a conversion to the coordinates of the sprite on the sprite sheet.

At the moment, this is conversion string-> integer, integer-> string, integer-> Coord, etc. happens in several places in the code using the case statement. It stinks, of course, and I would prefer to do it with a dictionary search.

I created a class called levelInfo and want to define a dictionary for this conversion, and then class methods to call when I need to do the conversion, or otherwise process the level data.

NSString *levelObjects = @"empty,player,object,thing,doohickey"; int levelIDs[] = [0,1,2,4,8]; // etc etc @implementation LevelInfo +(int) crateIDfromChar: (char) crateChar { int idx = [[crateTypes componentsSeparatedByString:@","] indexOfObject: crateChar]; return levelIDs[idx]; } +(NSString *) crateStringFromID: (int) crateID { return [[crateTypes componentsSeparatedByString:@","] objectAtIndex: crateID]; } @end 

Is there a better way to do this? It is wrong to build these temporary arrays or dictionaries or something else for every call for this translation. And I don't know how to declare a constant NSArray or NSDictionary.

Please tell me the best way ...

+4
source share
2 answers

If you want the array to be accessible for all the code in your class, just declare it outside the context of @implementation , and then initialize it in your class +initialize .

 NSArray *levelObjects; @implementation LevelInfo + (void) initialize { if (!levelObjects) levelObjects = [[NSArray alloc] initWithObjects:@"empty",@"player",@"object",@"thing",@"doohickey",nil]; } // now any other code in this file can use "levelObjects" @end 
+13
source

Declare it static , so it needs to be created only once.

+3
source

Source: https://habr.com/ru/post/1306646/


All Articles