static
in Objective-C means a different thing than static
in a C++ class, in the context of static class data members and static class methods. In C and Objective-C, a static
variable or function at global scope means that that symbol has internal linkage.
Internal linkage means that that symbol is local to the current translation unit, which is the current source file (.c
or .m
) being compiled and all of the header files that it recursively includes. That symbol cannot be referenced from a different translation unit, and you can have other symbols with internal linkage in other translation units with the same name.
So, if you have a header file declaring a variable as static
, each source file that includes that header gets a separate global variable—all references to that variable within one source file will refer to the same variable, but references in different source files will refer to different variables.
If you want to have a single global variable, you can't have it in class scope like in C++. One option is to create a global variable with external linkage: declare the variable with the extern
keyword in a header file, and then in one source file, define it at global scope without the extern
keyword. Internal linkage and external linkage are mutually exclusive—you cannot have a variable declared as both extern
and static
.
An alternative, as Panos suggested, would be to use a class method instead of a variable. This keeps the functionality within the scope of the class, which makes more sense semantically, and you can also make it @private
if you so desire. It does add a marginal performance penalty, but that's highly unlikely to be the bottleneck in your application (if you suspect it is, always profile first).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…