Tom Lilletveit
Tom Lilletveit

Reputation: 2002

What is the standard for sharing constant defined variables

As the title says - in Java I would just make a class define the constants then import them into the classes that will be using them. Is it done the same way in Objective-C?

To make it clear, I want to

#define variable 1
#define variable 2.0

And use the same constants in different classes.

Upvotes: 3

Views: 1057

Answers (3)

puzzle
puzzle

Reputation: 6131

Your example is using C preprocessor macros. This works the same with Objective-C as in any other environment supporting C-style preprocessor macros: Stick them into a shared header and #import or #include it.

While that's perfectly ok, you were asking about class-related constants and Objective-C in particular. In Objective-C you'll often see constant NSStrings (e.g. for notification names or dictionary keys) and similar constants belonging to a specific class defined like this:

In the header (.h):

extern NSString * const LibraryEntryDidUpdateNotification;
extern const NSUInteger LibraryEntryDefaultStarRating;

@interface LibraryEntry : NSObject

...

In the implementation (.m):

NSString * const LibraryEntryDidUpdateNotification = @"LibraryEntryDidUpdateNotification";
const NSUInteger LibraryEntryDefaultStarRating = 3;

@implementation LibraryEntry

...

This is how Apple does it in their modern frameworks, and how it is done by many 3rd party developers. In my opinion it's easier to refactor than preprocessor macros (e.g. when renaming a class using the "refactor" button in Xcode, the same easily works with these constants), but preprocessor macros for constants do have their benefits as well.

See here and here for a more in-depth discussion of the topic in case you're interested.

Upvotes: 1

rmaddy
rmaddy

Reputation: 318804

There is another alternative to using macros. You can define them as global variables.

In Constants.h:

extern int variableX;
extern float variableY;

In Constants.m (typically after the imports, before any other code):

int variableX = 1;
float variableY = 2.0f;

There are a few advantages to this approach over macros:

  1. Clients don't need to see the value.
  2. If the value(s) change, there is no need to recompile every file that imports Constants.h.
  3. The values can be initialized many different ways, not just with literals.
  4. Type safety and compiler checking when you use the variables.

Upvotes: 3

user529758
user529758

Reputation:

Put the macros in a header file, and #include or #import that header file whenever you need to access them.

Upvotes: 3

Related Questions