Use of extern in Objective C

It depends on what do you use it for. It is perfectly valid to use it to access to globally defined constants.
If you have a global object, however, I'd suggest using Singleton instead.


There are some use cases for the extern keyword in Objective-C.
Aaron Hillegass suggests to create global notification names extern. e.g.:

extern NSString* const XYYourNotification;

You then define the actual NSString* in your implementation


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.

Tags:

Objective C