Obj-C 枚举“初始化中的不兼容类型”
我遇到了枚举类型初始化的问题,这似乎很容易解决,但我还没有弄清楚如何做到这一点。 假设我声明以下枚举类型:
typedef enum NXSoundType {
NXSoundTypeNone,
NXSoundTypeEffect,
NXSoundTypeBackgroundMusic
} NXSoundType;
我声明一个方便的方法,用于返回给定一个像这样的 NSString 对象的 NXSoundType 枚举类型之一(注意:NXSound 是一个包含名为“type”的 NXSoundType 属性的对象):
- (NXSoundType)nxSoundTypeFromIdentifier:(NSString*)nxSoundIdentifier {
NXSoundType type = NXSoundTypeNone;
for (NXSound *nxSound in self.nxSounds) {
if ([nxSound.identifier isEqualToString:nxSoundIdentifier]) {
type = nxSound.type;
}
}
return type;
}
到目前为止,一切顺利。但以下调用不起作用:
NXSoundType type = [self nxSoundTypeFromIdentifier:@"kNXTargetGameSoundIdEffectTic"];
出了什么问题? 先感谢您。
I'm having a problem with enum type initialization that appears to be simple to solve but I haven't figured out how to do it.
Suppose I declare the following enum type:
typedef enum NXSoundType {
NXSoundTypeNone,
NXSoundTypeEffect,
NXSoundTypeBackgroundMusic
} NXSoundType;
I declare a convenience method for returning one of the NXSoundType enum types given a NSString object like this (NOTE: NXSound is an object that contains a NXSoundType attribute named "type"):
- (NXSoundType)nxSoundTypeFromIdentifier:(NSString*)nxSoundIdentifier {
NXSoundType type = NXSoundTypeNone;
for (NXSound *nxSound in self.nxSounds) {
if ([nxSound.identifier isEqualToString:nxSoundIdentifier]) {
type = nxSound.type;
}
}
return type;
}
So far, so well. But the following call is not working:
NXSoundType type = [self nxSoundTypeFromIdentifier:@"kNXTargetGameSoundIdEffectTic"];
What's wrong?
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我解决了这个问题。尽管出现编译器错误消息,但问题与错误的枚举类型声明/初始化无关。问题在于该方法
被定义为基类中的私有方法并被子类调用。这样,由于 Obj-C 的动态特性,预计会返回一个无法分配给
NXSoundType
枚举(仅分配给对象)的id
。一个简单的转换消除了问题,解决方案是将方法调用更改为:感谢所有回复,并对任何混淆表示歉意。希望这对某人有帮助。
I solved the problem. Despite the compiler error message, the problem was not related to wrong enum type declaration/initialization. The problem was that the method
was defined as a private method in a base-class and was been called by a sub-class. In this way, due to the Obj-C dynamic nature, it was expected to return an
id
which cannot be assigned to theNXSoundType
enum (only to objects). A simple cast removed the problem, the solution was to change the method call to:Appreciate all replies and sorry for any confusion. Hope this helps somebody.
尝试使用 just:
看看是否有帮助。 typedef 和名称相同可能会使 Obj-C 编译器感到困惑 喜欢这个人的问题。
Try using just:
and see if that helps. having the typedef and name be the same might be confusing Obj-C compiler like this person's question.