Wednesday, July 30, 2014

iOS define local and global NSString constant

situee.blogspot.com

1. Local Constant

There are two type of constants.

(1)  static NSString * const kMyConstant = @"constant string";

(2)  #define kMyConstant @"constant string"


"static const" is a better way, although "#define" is much shorter,

Here are some reasons:

  • "#define" are not type-safe. 
  • We can test the value of the "static const" constant with debugger;
  • Memory. Preprocessor create a new string each time the macro appear, while "static const" reuse the same string.

2. Global Constant

----------------  .h file  --------------

extern NSString *const kMyConstant;

----------------  .m file  --------------
// define in a .m file OUTSIDE @implementation like...

NSString *const kMyConstant = @"my constant";

The extern declaration says that there exists an NSString * const by the name kMyConstant whose storage is created in some other place.[1]

Remove the static -- that specifies that kMyConstant is only visible in files linked with this one.[1]



situee.blogspot.com

Reference:

 [1] http://stackoverflow.com/a/11942513/111277

http://stackoverflow.com/questions/1937685/static-nsstring-usage-vs-inline-nsstring-constants

No comments:

Post a Comment