Since there is new NSNumber
literals in Objective-C that you can use, for instance:
NSNumber *n1 = @1000; // [NSNumber numberWithInt:1000]
But it doesn't seem to be possible to use together with enums? I have tried:
typedef enum {
MyEnumA = 0,
MyEnumB,
MyEnumC
} MyEnum;
NSNumber *n2 = @MyEnumA; // [NSNumber numberWithInt:MyEnumA]
But I get a compiler error saying:
Unexpected '@' in program
I don't understand why it doesn't work since an enum is an int? Is there a way to make this work?
For named constants, you need to use @(MyEnumA)
.
You need to use:
NSNumber *n2 = @(MyEnumA);
I know it's odd, but it's just the way it is. I can't think off the top of my head but I assume the parser needs the parentheses in order to distinguish between different syntax.
What I tend to do is to use parentheses always. That works with normal numbers as well as enums as well as equations like:
int a = 2;
int b = 5;
NSNumber *n = @(a*b);
Others have explained what the proper syntax is. Here's why:
@blah
is called the "literal" syntax. You use it to make objects wrapping a literal, like a char, BOOL, int, etc. that means:
@42
is a boxed int@'c'
is a boxed char@"foo"
is a boxed char*@42ull
is a boxed unsigned long long@YES
is a boxed BOOLAll of the things following the at sign are primitive values. MyEnumValue
is not a literal. It's a symbol. To accommodate this, generic boxing syntax was introduced:
@(MyEnumValue)
You can put a bunch of things inside the parentheses; for the most part, any sort of variable or expression ought to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With