Ruby-style Class Constants?

Discussion in 'Mac Programming' started by jardeon, Feb 5, 2009.

  1. macrumors newbie

    Joined:
    Jul 29, 2007
    #1
    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:

    Code:
    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:

    Code:
    
    - (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!
     

Share This Page