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?
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants. A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.
The public|private static final TYPE NAME = VALUE; pattern is a good way of declaring a constant.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With