views:

1057

answers:

2

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?

+4  A: 

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.

e.James
It will also work in position 2 — or anywhere else before the enum is actually used — but it's visually more awkward anywhere but position 1.
Chuck
@Chuck: Good point. I didn't even think to check if it would work in positions #2 and #3. Position #1 is the way to go.
e.James
Thanks for the answer, this link: http://stackoverflow.com/questions/707512/typedef-enum-in-objective-c/707572#707572 explains why you need to place it after the braces.
Senseful
@eagle: Nice find on that link. You can always count on Mr. Rosenfield to provide a quality answer :)
e.James
+1  A: 

It looks like you are simply missing the ; off the end of the typedef enum declaration.

Peter N Lewis