Use of Static in Objective

Note: My question is not related to this.

Besides the variable not being seen outside the file it is declared in, in terms of memory allocation , is there any difference between declaring this (outside of a method):

NSString *const kMyConstant = @"Hello World";

Or this:

static NSString *const kMyConstant = @"Hello World";

In terms of memory allocation, no, there's no difference. Both variables are pointers to the same string constant, both are allocated once, and in both cases, their lifetime is the lifetime of the program.


No, there is not, it simply effects the visibility of the object outside the compilation unit.

This can also be achieved using:

__attribute__ ((visibility ("hidden")) NSString *const kMyConstant = @"Hello World";

EDIT That is cobblers; the visibility hidden attribute affects visibility outside of a shared object, not the compilation unit.


I think this is a very interesting question, since it shows some clear and understandable management of constants on one hand and some obvious exceptions that Objective C and clang include when handling NSString class constants.

I believe the following does apply:

Above declarations and initializations from the question make no difference to memory management. It simple doesn't really exist. Constants are simply included in bundle and are not allocated in classic terms. Meaning that value from object class is pointing to bundle memory location where string constant is. You can easily find this out when comparing address of such NSString and its object class. String address is very low, pointing to the bundle location addresses range. You can see that addresses of other strings that were initialized in the code point to a very different locations. Objective C runtime doesn't perform any kind of memory management on string constants, since it would be quite awkward to "release" or delete something from bundle. So, if you play with this in non-ARC environment, you will see that retain and release are simply ignored.

To end this by answering the question: no, there isn't any difference managing memory in both cases. It's simply not done. Memory is allocated by bundle and it is released by OS when application ends. It doesn't apply only for declarations and assigning explicit constant outside the implementation, but also inside any method.

链接地址: http://www.djcxy.com/p/73960.html

上一篇: 在线支付服务与最好的NodeJS库/包装

下一篇: 在目标中使用静态