What is the difference between const NSString and static NSString

I want to use a class variable. The following two approaches work well, but I do not know what is different between them.

static NSString *str1 = @"str1"; NSString *const str2 = @"str2"; @implementation StrViewController 
+4
source share
2 answers

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

this will work:

 str1 = @"Hello"; 

until it is:

 str2 = @"Hello"; 
+5
source

I think you will find that your variable should not be static or const ! What makes it a class variable is outside of any method or function.

Despite the name, static has nothing to do with the fact that it is static (i.e., remains the same). This is a very bad choice of terminology, but it comes from C and we are stuck with it. static refers to the scope of the variable; it is implemented at the file level, within the file size, but outside of any specific methods / functions. It is used in two ways:

  • Outside of any method or function, static prevents a global variable from being viewed from outside the file. See Link to static NSString * const from another class .

  • Within a method or function, static associates the repository with the file as a whole, and the variable goes out of existence when the method or function ends as an “automatic” variable does. Like the inventors of C themselves, (K & R 4.6):

Unlike automation, they are restored, not come and go every time the function is activated. This means that the static internal variables provide private persistent storage as part of a single function.

This is why static used when implementing a singleton class.

+1
source

Source: https://habr.com/ru/post/1438836/


All Articles