Constants in Objective-C

Recently I was working on a legacy project written in Objective-C, which reminded me of the early days when working on Objective-C projects.

In the code I saw few things like the following which defines a constant:

#define car_price 300

#define creates a macro which simply do the replacement for the compiler. In the above code, compiler doesn't know the type of the card_height. It must be converted to a float value when using. So it is not type-safe.

Instead of using a macro to define a constant, it is a better way to use const to define a constant as it is type-safe and easier to debug.

static float const kCarPrice = 300.0f; 

Also we can use const to define other types of constants too.

static NSString* const kCarModel = @"Lexus IS 200T"; 
static in const KCarType = 1;

Noticed that const can only used before immutable variables. So the following two statements are the same, both kCarModel1 and kCarModel2 are immutable, even if they have the type of NSMutableString.

static NSString* const kCarModel1 = @"Lexus IS 200T"; 
static NSMutableString* const kCarModel2 = @"Lexus IS 200T"; 
comments powered by Disqus