const VS静态NSStrings在Objective-C [英] const vs static NSStrings in Objective-C
问题描述
这些行都在 @implementation
声明之上的实现文件中。
NSString * const aVar = @aVarStringValue;
static NSString * aVar = @aVarStringValue;
据我所知,第二个 static
仅在应用程序的生命周期内分配一次,这个事实有助于性能。
但这是否意味着它本质上是一个内存泄漏,不会被释放?
每次访问时,第一个 const
Objective-C(和C / C ++)中的p>
static
变量的可见性。静态变量(不在方法中)只能在特定的 .m
文件中访问。另一方面,静态局部变量只被分配一次。另一方面,
const
该引用可以不被修改和/或重新分配;
值得一提的是 NSString
文字被初始化,永远不会在应用程序的生命中被破坏。它们分配在内存的只读部分。
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?
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.
这篇关于const VS静态NSStrings在Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!