4

I want to use class variable. the following two approaches work well, but I don't know what's the different between them.

static NSString *str1 = @"str1";
NSString *const str2 = @"str2";
@implementation StrViewController
user1687717
  • 3,375
  • 7
  • 26
  • 29

2 Answers2

5

you can change the location to where str1 is pointing to but cannot do the same for str2 as it is a const pointer

this will work :

str1 = @"Hello";

while this won't:

str2 = @"Hello"; 
giorashc
  • 13,691
  • 3
  • 35
  • 71
  • so there's no difference except changeable? – user1687717 Oct 10 '12 at 09:18
  • not exactly. Depends on the scope. In a function for example the initialization of static is made only once (even on multiple calls to the function) while the const variable will be initialized on each call – giorashc Oct 10 '12 at 09:32
  • @giorashc , what about static NSString *const str2 = @"str2"; –  Oct 24 '12 at 11:05
  • in what context ? you cannot change the address str2 is pointing to since str2 is a const pointer – giorashc Oct 24 '12 at 14:07
1

I think you'll find that your variable needn't be static or const! What makes it a class variable is that it's outside any method or function.

Despite the name, static has nothing to do with being static (i.e. staying the same). It's a very unfortunate choice of terminology, but it comes from C and we're stuck with it. static has to do with the scope of a variable; it is implemented at the level of the file, within the scope of the file but outside of any particular methods/functions. It is used in two ways:

  • Outside any method or function, static prevents a global variable from being seen from outside this file. See Referencing a static NSString * const from another class.

  • Inside a method or function, static ties the storage to the file as a whole rather having the variable go out of existence when the method or function ends the way an "automatic" variable does. As the inventors of C themselves put it (K&R 4.6):

Unlike automatics, they remeain in existence rather than coming and going each time the function is activated. This means that internal static variables provide private, permanent storage within a single function.

That is why static is used in the implementation of class-vended singleton.

Community
  • 1
  • 1
matt
  • 515,959
  • 87
  • 875
  • 1,141