R – Can an enum be defined in the same file as a class header that uses it in Objective-C

enumsheader-filesobjective c

If not, and it needs to be included in a separate file (e.g. MyEnums.h) do I need to #import MyEnums.h every time a .m or .h file wants to refer to the type or one of the values?


Here's sample code of MyClass.h:

#import <Foundation/Foundation.h>

// #1 placeholder

@interface MyClass : NSObject {
}

// #2 placeholder

- (void)sampleMethod:(MyEnum)useOfEnum;

// #3 placeholder

@end

Here's the enum I'm trying to define:

typedef enum MyEnum {
    Value1,
    Value2
}

If I try placing my enum definition in #1, I get error: no type or storage class may be specified here before 'interface'.

If I try placing my enum definition in #2, I get error: expected identifier or '(' before 'end'.

If I try placing my enum definition in #3, I get error: expected ')' before 'MyEnum'. Which is complaining about the parameter "useOfEnum" because it's type is not defined yet.


So can this be done? Or what is the best way to do this and limit the amount of #imports required?

Best Answer

It should work in position #1, but I think you need to write it like so:

typedef enum {
    Value1,
    Value2
} MyEnum;

To work properly.

update: I have confirmed this (at least in Xcode 3.2). The syntax shown above compiles without errors.

Related Topic