Use of extern in Objective C

后端 未结 5 1675
无人及你
无人及你 2020-12-07 11:30

How good is it to use extern in Objective C? It does make coding for some parts easy.. but doesn\'t it spoil the object orientation?

5条回答
  •  时光说笑
    2020-12-07 11:42

    You'll find that extern is used extensively in the Cocoa frameworks, and one would be hard-pressed to find a convincing argument that their OO is "spoiled". On the contrary, Cocoa is well-encapsulated and only exposes what it must, often via extern. Globally-defined constants are certainly the most common usage, but not necessarily the only valid use.

    IMO, using extern doesn't necessarily "spoil" object orientation. Even in OO, it is frequent to use variables that are accessible from anywhere. Using extern is the most frequent workaround for the lack of "class variables" (like those declared with static in Java) in Objective-C. It allows you to expand the scope in which you can reference a symbol beyond the compilation unit where it is declared, essentially by promising that it will be defined somewhere by someone.

    You can also combine extern with __attribute__((visibility("hidden"))) to create a symbol that can be used outside its compilation unit, but not outside its linkage unit, so to speak. I've used this for custom library and framework code to properly encapsulate higher-level internal details.

提交回复
热议问题