These lines are both in the implementation file above the @implementation
declaration.
NSString * const aVar = @"aVarStringValue"; static NSString *aVar = @"aVarStringValue";
As far as I understand, the second static
is allocated once only within the lifetime of the application and this fact contributes to performance.
But does this mean it is essentially a memory leak seeing as that block of memory will never be released?
And does the first const
declaration get allocated every time it is accessed in contrast?
const means that you're not changing the value after it has been initialised. static inside a function means the variable will exist before and after the function has executed. static outside of a function means that the scope of the symbol marked static is limited to that . c file and cannot be seen outside of it.
The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.
They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.
"In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.
static
keyword in Objective-C (and C/C++) indicates the visibility of the variable. A static variable (not in a method) may only be accessed within that particular .m
file. A static local variable on the other hand, gets allocated only once.
const
on the other hand, indicates that the reference may not be modified and/or reassigned; and is orthogonal on how it can be created (compilers may optimize consts though).
It's worth mentioning that NSString
literals get initialized and never get destroyed in the life of application. They are allocated in a read-only part of the memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With