How to define constants correctly

Possible duplicate:
Constants in Objective-C

I am designing a controller and I need some constants inside it (locally, only for this controller). Looking at the sample code provided by Apple, I 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 someone explain to me what is the difference between the two? What style should I use? Are they dependent on the type of object / value you assign to them? The value is used: static NSString * for strings, #define for float, and NSInteger for integers? How do you make a choice?

+7
source share
2 answers

The #define keyword is a compile-time directive that causes a direct embedding of the define'd value in your code. It is global throughout the program and all related libraries. Thus, you can remove this from the list based on your desire to create a constant only for the controller .

The main difference between static and const is that static variables can be changed after initialization, const cannot. If you want to change your variable after initialization, you must use a static keyword.

Hope this helps.

+5
source

Since Scott and Benzado have indicated this is the best way to determine your constant values. However, as far as this is defined, it is more difficult to debug using definitions, since usually you cannot easily see the extended value in the debugger. You will need to add the extern declaration to the header file of your class if your intent is to expose the variable globally. And the next thing to keep in mind is to place a const declaration after the pointer (*), otherwise you will get warnings about dropping qualifiers from the pointer in most cases.

0
source

All Articles