Objective-C equivalent of Java enums or “static fi

2020-07-18 04:32发布

问题:

I'm trying to find an Objective-C equivalent to either Java enum types, or "public static final" objects, like:

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 that are constants (of course), and accessible anywhere that imports the associated .h file, or globally. I've tried the following with no 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 FOO constant, it had no values in the str and val variables. I have verified through the use of NSLog calls that initialize is in fact being called.

Also, even though I am referencing 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 totally baffled! Thanks for any help!

回答1:

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's 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 a single compilation unit (e.g., a single .m file). So using static in a header file will create private FOO instances for each .m file that includes Foo.h, which is not what you would ever want.