开发者

How do I declare a class property as an enum type

开发者 https://www.devze.com 2022-12-17 14:26 出处:网络
I want to declare a custom enum such as: enum menuItemType { LinkInternal = 0, LinkExternal = 1, Image = 2,

I want to declare a custom enum such as:

enum menuItemType
{
    LinkInternal = 0,
    LinkExternal = 1,
    Image = 2,
    Movie = 3,
    MapQuery = 4
}

As a type for my object:

@in开发者_StackOverflow社区terface MenuItem : NSObject {    
    NSMutableString *menuId;
    NSMutableString *title;
    enum menuItemType *menuType;
    NSMutableArray *subMenuItems;
}

But am unsure where I need to put the enum definition - if I put it before the @interface its syntactically incorrect


Just updating this in case someone stumbles upon this in our future times.

Since iOS 6 / Mac OS X 10.8, the new NS_ENUM and NS_OPTIONS macros are the preferred way to declare enum types.

In that case, it would look like:

typedef NS_ENUM(NSInteger, MenuItemType) {
    LinkInternal = 0,
    LinkExternal = 1,
    Image = 2,
    Movie = 3,
    MapQuery = 4
};

@interface MenuItem : NSObject {    
    NSMutableString *menuId;
    NSMutableString *title;
    MenuItemType menuType;
    NSMutableArray *subMenuItems;
}

A good read on the subject: http://nshipster.com/ns_enum-ns_options/

You might also want to conform to Apple's conventions for enum naming and go for something like:

typedef NS_ENUM(NSInteger, MenuItemType) {
    MenuItemTypeLinkInternal = 0,
    MenuItemTypeLinkExternal = 1,
    MenuItemTypeImage = 2,
    MenuItemTypeMovie = 3,
    MenuItemTypeMapQuery = 4
};

Hope this will help.


If you put your two code snippets in a file in this order, you just have to add a ; at the end of the enum declaration and you may want to consider using an enum variable instead of a pointer to an enum variable.

This gives:

enum menuItemType
{
    LinkInternal = 0,
    LinkExternal = 1,
    Image = 2,
    Movie = 3,
    MapQuery = 4
};

@interface MenuItem : NSObject {    
    NSMutableString *menuId;
    NSMutableString *title;
    enum menuItemType menuType;
    NSMutableArray *subMenuItems;
}


@mouviciel is right, but I thought I'd let you know that what you want is not a class property, something not supported in Objective-C. A class property is actually a global property that is set on the class-object. What you were thinking of was a plain-old property (set on an instance of the class).

Also, what your code shows is that you are just using an instance variable. Instance variables can be turned into properties by adding accessor/mutator methods as follows:

// after @interface {}
@property (readwrite) enum menuItemType menuType;

and

// under @implementation
@synthesize menuType;

This is a shortcut: the compiler will generate the proper methods to access and change the menuType property. I'm not sure how useful all this is to you, but it will help you with your understanding of Objective-C semantics.

0

精彩评论

暂无评论...
验证码 换一张
取 消