Chris
Chris

Reputation: 7310

Objective C: Accessing constants from other classes

I have a constant in one class that I want to access from another. I want to access these:

#define kStateRunning 1
#define kStateGameOver 2
#define kStateMenu 3

which are in my GameController.h from Level1.m. In Level1.h I have @class GameController as well as an import in the implementation file.

I tried searching for an answer, but I'm not sure if I'm wording all this correctly.

Upvotes: 2

Views: 3663

Answers (2)

Paul.s
Paul.s

Reputation: 38728

I wouldn't use #define as you lose any checking from the compiler. Generally you use a constant to avoid using magic values throughout your code that can be spelt wrong or typed wrong.

In the Apple docs for Coding Guidelines they tell you how you should approach each type of constant.

For simple integers like you have, they suggest enums are the best option. They are used extensively in the Apple frameworks so you know they are good.

You would still need to define it in your header.

e.g. (Use your own prefix instead of PS)

typedef enum {
    PSGameStateRunning  = 1,
    PSGameStateGameOver,
    PSGameStateMenu,
} PSGameState;

This also has the advantage of being a type that you can pass into/return from functions if you require

Upvotes: 3

Zoleas
Zoleas

Reputation: 4879

If you use #define myConstant, myConstant will be known since you import your file. Define them at the beginning of your GameController.h between the import and the @Interface for example.

Then if you import GameController.h in one of your other files (let's take Level1.m for example). You can use it, without prefixing it. Just use myConstant

Upvotes: 6

Related Questions