Sunday, June 13, 2010

Declaring constants in Objective-C

Yes, I'm back! Sadly my last post was in January, but I'm hoping to get back on the wagon here adding tips and tricks. Today I'll bring you the rather simple task of declaring and using constants in Objective-C. Let's assume you want to declare an NSString constant in your class that holds a url. In your header .h file you will need the following:

#import 

extern NSString * const BaseURL;

@interface ClassName : NSObject {

You will then need to set it's value in your main .m file as follows:

#import "ClassName.h"

NSString * const BaseURL = @"http://some.url.com/path/";

@implementation ClassName

You can now access this constant throughout your class or subclasses. Here's an example of usage:

NSString *urlString = [NSString stringWithFormat:@"%@%@", BaseURL, @"filename.html"];