ugur
ugur

Reputation: 842

How to hide the constants I defined in static library?

I have a library of my own. And there are lots of constants defined in headers (for example animation duration). But, all my headers are visible and changeable. How can I prevent others to change my default values?

There are some const value in headers of Apple libraries like this:

CA_EXTERN NSString * const kCATransitionMoveIn __OSX_AVAILABLE_STARTING (__MAC_10_5, __IPHONE_2_0);

Upvotes: 1

Views: 492

Answers (1)

Jody Hagins
Jody Hagins

Reputation: 28409

Objective-C is still, well, C. Maybe older systems had issues, which is why you see the macros there. Anyway, you should still be safe with any built-in type.

If you declare something as "extern" the compiler will treat it something like, "OK, I see that someone has declared and external thingy. I don't have to know what it is, because some external unit will define it. The linker will handle the rest.

That paragraph will get me in trouble with the C-police, but it's close enough for a practical explanation. Thus, you can do this in your header file...

extern int const TheAnswerToLifeTheUniverseAndEverything;

And then, in one of your implementation files (outside of the @implementation/@end section)...

int const TheAnswerToLifeTheUniverseAndEverything = 42;

Note, in "modern" Xcode versions, you can do the same thing with objects. Note the "const" which means we have a constant-pointer-to-NSString.

// In header
extern NSString * const TheAnswerToLifeTheUniverseAndEverythingString;

// In source
NSString * const TheAnswerToLifeTheUniverseAndEverythingString = @"42";

Upvotes: 3

Related Questions