Obj-C enum "Incompatible Types in initialization"
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,开发者_如何学Go so well. But the following call is not working:
NXSoundType type = [self nxSoundTypeFromIdentifier:@"kNXTargetGameSoundIdEffectTic"];
What's wrong? Thank you in advance.
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
- (NXSoundType)nxSoundTypeFromIdentifier:(NSString*)nxSoundIdentifier;
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 the NXSoundType
enum (only to objects). A simple cast removed the problem, the solution was to change the method call to:
NXSoundType type = (NXSoundType)[self nxSoundTypeFromIdentifier:@"kNXTargetGameSoundIdEffectTic"];
Appreciate all replies and sorry for any confusion. Hope this helps somebody.
Try using just:
typedef enum {
NXSoundTypeNone,
NXSoundTypeEffect,
NXSoundTypeBackgroundMusic
} NXSoundType;
and see if that helps. having the typedef and name be the same might be confusing Obj-C compiler like this person's question.
精彩评论