Enum defining forms in Objective-C

What is the difference between

typedef enum {
    ...
} Name;

and

enum {
    ...
};
typedef NSUInteger Name;

? If functionality is the same, what is the second form good for? Isn't it unnecessarily messy?

===============================================================================

The former defines a type name to refer to an enum. This is the way most enums are named in C. The latter is a bit different though, and it's prevalent in the Cocoa frameworks. There's two reasons to use the latter. The first is if your enum defines a bitfield, and you'd want it here because when you're providing a "Name" value you'll be providing a combination of the enum values. In other words, if you say something like

[self doSomethingWithBitfield:(Enum1 | Enum2)]

you're not passing a value of Name but rather an integer that's a combination of the two.

However, Cocoa frameworks use this idiom even for non-bitfield values, for a very good reason: API stability. According to the C standard, the underlying integral type of an enum is requires to be able to contain all values in the enum, but is otherwise chosen by the compiler. This means that adding a new enum value could change the integral type of the enum (e.g. adding -1 can make it signed, adding 6 billion can make it into a long long, etc). This is a bad thing from an API stability standpoint, because the type encoding of methods which take values of this enum could change unexpectedly and potentially break existing code and binaries. In order to prevent this, the Cocoa frameworks generally define the type as being an NSUInteger (or NSInteger if they need negative numbers), so the API and type encodings stay stable.

转载自:http://stackoverflow.com/questions/7421516/enum-defining-forms-in-objective-c

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值