PDA

View Full Version : Ruby-style Class Constants?




jardeon
Feb 5, 2009, 07:51 AM
Hi everyone,

As a recent arrival on the Obj-C scene, I'm still wrestling with a few concepts.

Does Objective C provide a similar functionality to Ruby's class constants?

In Ruby, I could do the following:


class PolygonShape
attr_accessor :number_of_sides
NAMES = { "3" => "triangle", "4" => "tetragon", "5" => "pentagon" }

def name
NAMES[self.number_of_sides]
end
end


I'd like to do something similar in Obj-C, define an NSDictionary of terms that's constant to the class, and not have to re-instantiate it on each run. Currently, I'm doing the following:



- (NSDictionary *)names {
NSDictionary *names = [NSDictionary dictionaryWithObjectsAndKeys:@"triangle", @"3", @"tetragon", @"4",
@"pentagon", @"5", nil];
return names;
}

- (NSString *)name {

NSString *polygon_name = [[self names] objectForKey:[NSString stringWithFormat:@"%d", [self numberOfSides]]];
return polygon_name;
}



Thanks!