views:

298

answers:

2

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?

+12  A: 

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.

notnoop
Wish I could give you a tick, but bbum was first.
firstresponder
I upvoted notnoop's answer... it is a good one. :)
bbum
+10  A: 

The static only changes the scope of the variable, not how it is declared or stored.

In both cases, the compiler will create a constant version of the NSString instance that is stored in the mach-o file. Thus, there is only ever one instance of either (note that you can change the behavior to cause the string to be dynamically created on load of the mach-o, but there is still just one instance).

The static just marks the aVar variable as being visible within the scope of the compilation unit -- the file -- only. Without the static, you could redeclare the string as extern NSString *aVar; in a header somewhere and have access to it from anywhere.

The const is orthogonal and, in the case of of NSString reference is pretty much entirely irrelevant.

bbum
Thanks. This bit: 'you could redeclare the string as extern NSString *aVar; in a header somewhere and have access to it from anywhere' really drove it home for me.
firstresponder