Enums in Objective-C?

Member
Posts: 61
Joined: 2009.01
Post: #1
This is a syntax-based question. I'm having a bit of trouble getting enums working in Objective-C. I'm also not sure where the best place to declare them is, but within @implementation seems like it would be fine.

Code:
@implementation

typedef enum animalTypes
{
     DOG,
     CAT,
     MONKEY,
     MONGOOSE
} Animals;

- (void) doStuff
{
     int x = Animals.DOG;
     int y = (int) Animals.DOG;
}

@end

That's what I've been trying. The enum declaration works fine, but neither of the two assignments in doStuff are legal. Can someone just write out the proper way of doing this? Thanks.
Quote this message in a reply
Moderator
Posts: 1,560
Joined: 2003.10
Post: #2
enum in C (and thereby Objective-C) is simply syntactic sugar for #define, plus a little bit of type safety. The way you're written that code, "enum animalTypes" and "Animals" are both integer types that will require all values thereof to be handled in any switch statement on variables of that type. DOG, CAT, MONKEY, and MONGOOSE are all constants that can be used directly without any prefix.
Quote this message in a reply
Member
Posts: 254
Joined: 2005.10
Post: #3
You can actually put your enums just about anywhere you want. In your example, you could put the enum outside of the implementation or inside it, but I would keep it in the .m file since it's just a part of the implementation details. My personal style would be to list it before the @implementation keyword.

If you were going to use an enum to define some constants to use a parameters to a method you should put it in the header file instead so clients can just import the header. In that case I would highly recommend keeping the enum outside of the @interface declaration. I'm not certain that it would matter syntactically, but it makes the most sense semantically.
Quote this message in a reply
Member
Posts: 34
Joined: 2009.01
Post: #4
So, the gist is that the OP should just do the following, correct?

Code:
@implementation

typedef enum animalTypes
{
     DOG,
     CAT,
     MONKEY,
     MONGOOSE
} Animals;

- (void) doStuff
{
     Animals x = DOG;
     int y = (int)DOG;
}

@end
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  How do you create enums for state charts in ObjC? riruilo 7 6,828 Mar 27, 2010 11:50 PM
Last Post: AnotherJake