Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New NSNumber literals

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?

like image 646
Peter Warbo Avatar asked Nov 08 '12 13:11

Peter Warbo


3 Answers

For named constants, you need to use @(MyEnumA).

like image 155
Wevah Avatar answered Oct 21 '22 04:10

Wevah


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);
like image 32
mattjgalloway Avatar answered Oct 21 '22 03:10

mattjgalloway


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 BOOL

All 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.

like image 41
Dave DeLong Avatar answered Oct 21 '22 05:10

Dave DeLong