Reputation: 2002
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
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
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:
Upvotes: 3
Reputation:
Put the macros in a header file, and #include
or #import
that header file whenever you need to access them.
Upvotes: 3