7

Possible Duplicate:
Constants in Objective C

I'm designing a controller and I'm gonna need some constants inside it (locally, just for that controller). Looking at some sample code provided by Apple, I can see these lines:

#import "Constants.h"

#define kTextFieldWidth 260.0

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

const NSInteger kViewTag = 1;

Can anyone explain to me what the difference between them is? Which style should I use? Are they dependent on the type of object/value you assign to them? Meaning use: static NSString * for strings, #define for floats and NSInteger for integers? How do you make the choice?

Community
  • 1
  • 1
Hidden
  • 129
  • 2
  • 4

2 Answers2

5

The #define keyword is a compile time directive that causes the define'd value to be directly injected into your code. It is global across the entire program and all linked libraries. So you can strike that off the list, based on your desire to create a constant for the controller only.

The main difference between static and const is that static variables can be changed after initialization, const ones cannot. If you want to be able to modify your variable after initialization then you should use the static keyword.

Hope that helps.

Perception
  • 75,573
  • 19
  • 170
  • 185
0

As Scott and benzado pointed out that is the best way to define your constant values. However as far as defines go it is harder to debug using defines as you can usually not easily see the expanded value in a debugger. You will only need to add an extern declaration to the header file of your class if your intentions are to expose the variable globally. And the next thing to remember is to put the const declaration after the pointer (*) or else you will get warnings of discard qualifiers from pointer in most uses.

Community
  • 1
  • 1
Joe
  • 55,599
  • 8
  • 122
  • 132