Reputation: 669
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).
Upvotes: 1
Views: 2318
Reputation: 29029
I am a Java programmer, […]
There's your problem right there.
Objective-C is a quite different language from Java in a lot of ways, and a lot of idioms may be quite foreign to you.
As an example; why do you want, or need, to know what kind of polygon shapes the Polygon class can handle?
If you are trying to create a polygon with a certain number of corners, but can't, then yes, you need to know.
Apart from that? Not very useful info, at least as far as I can see.
In fact, why would a polygon shape even need to know what other shapes exist?
Shed for a moment the very idea of static
, and reconsider your problem. Enlightenment is sure to follow.
Upvotes: 1