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
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
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";
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.