Peter Warbo
Peter Warbo

Reputation: 11690

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?

Upvotes: 6

Views: 833

Answers (3)

Dave DeLong
Dave DeLong

Reputation: 243146

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.

Upvotes: 2

Wevah
Wevah

Reputation: 28242

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

Upvotes: 17

mattjgalloway
mattjgalloway

Reputation: 34902

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);

Upvotes: 3

Related Questions