Typedef 枚举 Objective-C
我有类 Distance 和 typedef enum Unit,
@interface Distance:NSObject{
double m_miles;
}
@property double m_miles;
-(Distance *) initWithDistance: (double) value andUnit:(Unit) unit;
@implementation Distance
-(Distance *)initWithDistance: (double) value andUnit:(Unit) unit{
self = [super init];
if (self){
switch (unit) {
case Unit.miles: m_miles = value;
break;
case Unit.km: m_miles = value/1.609344;
break;
}
}
我在哪里声明我的 enum Unit?如何访问
typedef enum{
miles;
km;
}Unit
在另一个类中我应该能够调用 Distance.Unit.km
或英里:
Distance *a = [[Distance alloc] initWithDistance: 10.2 andUnit: Distance.Unit.km];
I have class Distance and typedef enum Unit,
@interface Distance:NSObject{
double m_miles;
}
@property double m_miles;
-(Distance *) initWithDistance: (double) value andUnit:(Unit) unit;
@implementation Distance
-(Distance *)initWithDistance: (double) value andUnit:(Unit) unit{
self = [super init];
if (self){
switch (unit) {
case Unit.miles: m_miles = value;
break;
case Unit.km: m_miles = value/1.609344;
break;
}
}
Where do I declare my enum Unit? How to access
typedef enum{
miles;
km;
}Unit
In the other class I should be able to call Distance.Unit.km
or miles:
Distance *a = [[Distance alloc] initWithDistance: 10.2 andUnit: Distance.Unit.km];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C 中,
enum
不会使其值“合格”。你必须通过以下方式访问它In C an
enum
doesn't makes its values "qualified". You have to access it with看起来您正在尝试像 C++ 中那样进行类 typedef 。我不记得 Objective-C 中是否允许这样做,但无论如何我都不会这样做。我会将枚举保留在类之外。只需使用 typedef 创建另一个头文件即可。尽管这是一个微不足道的示例,但该枚举在 Distance 类之外可能还有其他用途,因此请在外部定义它。
另一种可能性,如果这就是您使用它的全部目的,那就是有两个初始化器
initWithMiles:
和initWithKilometers:
。It looks like you are trying to do a class typedef like you can in say C++. I don't remember if that is even allowed in Objective-C but thats not how I would do it here anyway. I would keep the enum outside of the class. Just create another header file with the typedef. Though this is sort of a trivial example, there may be other uses for that enum outside of the Distance class so define it outside.
Another possibility, if this is all you are using it for is to have two initializers
initWithMiles:
andinitWithKilometers:
.Objective-C 不会改变 C 关键字的含义。它被设置为使用消息和对象。您应该在
@interface
之前声明enum
。我建议您按照 JeffW 使用initWithMiles:
并initWithKilometers:
,请参阅 Cocoa Fundamentals 了解如何设计方法。Objective-C does not change the sense of the C keywords. It is set to use the messages and objects. You should declare
enum
before@interface
. I suggest you to follow JeffW useinitWithMiles:
andinitWithKilometers:
, see Cocoa Fundamentals for how to design methods.