Objective-C equivalent of Java enumerations or "static target" objects

I am trying to find the equivalent of Objective-C for Java rename types or "public static destination" objects, for example:

public enum MyEnum { private String str; private int val; FOO( "foo string", 42 ), BAR( "bar string", 1337 ); MyEnum( String str, int val ) { this.str = str; this.val = val; } } 

or,

 public static final MyObject FOO = new MyObject( "foo", 42 ); 

I need to create constants, which are constants (of course), and are available anywhere where the linked .h file is imported or globally. I tried the following without success:

foo.h:

 static MyEnumClass* FOO; 

Foo.m:

 + (void)initialize { FOO = [[MyEnumClass alloc] initWithStr:@"foo string" andInt:42]; } 

When I did this and tried to use the constant FOO , it had no values ​​in the variables str and val . I checked with NSLog calls, which are actually called initialize .

Also, although I refer to the FOO variable in the test block of code, Xcode highlighted the line in the .h file shown above with the comment 'FOO' defined but not used .

I'm completely baffled! Thanks for any help!

+4
source share
1 answer

Use extern instead of static :

foo.h:

 extern MyEnumClass* FOO; 

Foo.m:

 MyEnumClass* FOO = nil; // This is the actual instance of FOO that will be shared by anyone who includes "Foo.h". That what the extern keyword accomplishes. + (void)initialize { if (!FOO) { FOO = [[MyEnumClass alloc] initWithStr:@"foo string" andInt:42]; } } 

static means that the variable is private within the same compilation unit (for example, a single .m file). Thus, using static in the header file will create private FOO instances for each .m file, which includes Foo.h, which you don't want.

+5
source

Source: https://habr.com/ru/post/1345804/


All Articles