Frage

I want to do something like this in Obj-C. Example:

extern float TRANSITION_TIME = 0.5f;

Or even better:

static float TRANSITION_TIME = 0.5f;

So then it is automatically imported with headers!

However, both give some kind of warning: 'extern' variable has an initializer

War es hilfreich?

Lösung

Try to separate the declaration like this

extern float TRANSITION_TIME;
float TRANSITION_TIME = 0.5f;

Although the situation is different, there's a nice explanation in this link.

Andere Tipps

You can do it quite easily as this :

#import <Cocoa/Cocoa.h>

static float TRANSITION_TIME = 0.5f;


@interface ClassName : NSObject
 ...// rest of codes goes here
@end

I assume you wish to define a single variable TRANSITION_TIME which is accessible in multiple locations and defined & initialised in one location.

There is a parallel here with a function or a method - you place a declaration for the function or method in a .h file, which is included in multiple locations; and define the function/method in a .m (or .c etc.) file, i.e you give it a value in one location.

To define your variable you follow the same pattern. In your .h file you declare your variable:

extern float TRANSITION_TIME;

you need to use extern to indicate this is a declaring a variable defined elsewhere[*] . Then in your .m file you provide the definition:

float TRANSITION_TIME = 0.5f;

[*] For function/method declarations in the .h the lack a body is sufficient to indicate the function/method is defined elsewhere and extern is assumed. However for functions you can also include the extern at the start of the declaration (the syntax for methods does not support this redundancy).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top