I am a Java programmer, learning Objective-C and I have a problem with implementation of variables, similar to static final class variables in Java. In class PolygonShape, I would like to have NSDictionary with polygon types, which can be accessed from within and outside of the class. I already tried the following:
PolygonShape.h:
...
extern NSDictionary *polygonTypes;
@interface PolygonShape
...
PolygonShape.m:
...
NSDictionary *polygonTypes = nil;
@implementation PolygonShape
- (id)init {
self = [super init];
if (self) {
if(!polygonTypes) {
polygonTypes = [NSDictionary dictionaryWithObjectsAndKeys:
@"triangle", [NSNumber numberWithInt: 3], @"quadrilateral", [NSNumber numberWithInt: 4],
@"pentagon", [NSNumber numberWithInt: 5], @"hexagon", [NSNumber numberWithInt: 6],
@"heptagon", [NSNumber numberWithInt: 7], @"octagon", [NSNumber numberWithInt: 8],
@"enneagon", [NSNumber numberWithInt: 9], @"decagon", [NSNumber numberWithInt: 10],
@"hendecagon", [NSNumber numberWithInt: 11], @"dodecagon", [NSNumber numberWithInt: 12], nil];
}
}
...
But this is not good enough, because if I want to access polygon types from elsewhere (e.g. main.m) without initializing instance of PolygonShape, variable polygonTypes is nil. So I used static function which works fine:
PolygonShape.m:
static NSDictionary *polygonTypes = nil;
@implementation PolygonShape
...
+ (NSDictionary *) polygonTypesDicionary {
if(!polygonTypes) {
polygonTypes = [NSDictionary dictionaryWithObjectsAndKeys:
@"triangle", [NSNumber numberWithInt: 3], @"quadrilateral", [NSNumber numberWithInt: 4],
@"pentagon", [NSNumber numberWithInt: 5], @"hexagon", [NSNumber numberWithInt: 6],
@"heptagon", [NSNumber numberWithInt: 7], @"octagon", [NSNumber numberWithInt: 8],
@"enneagon", [NSNumber numberWithInt: 9], @"decagon", [NSNumber numberWithInt: 10],
@"hendecagon", [NSNumber numberWithInt: 11], @"dodecagon", [NSNumber numberWithInt: 12], nil];
}
return polygonTypes;
}
Now this is ok, but I wonder, what is the best way to do this and is it possible to use extern for NSDictionary without having to initialize it in a class method? (and I know about singelton classes but I would really like to have constant array of polygon types inside PolygonShape class).