Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const vs static NSStrings in Objective-C

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?

like image 977
firstresponder Avatar asked Nov 27 '09 23:11

firstresponder


People also ask

What is the difference between const and static in C?

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.

What does const do in Objective C?

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.

Is it static const or const static?

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.

What is static in Objective C?

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


1 Answers

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.

like image 80
notnoop Avatar answered Oct 01 '22 09:10

notnoop