New NSNumber literals
Asked Answered
B

3

6

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?

Bergstein answered 8/11, 2012 at 13:26 Comment(0)
D
17

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

Deandra answered 8/11, 2012 at 13:27 Comment(2)
The reason is that Apple might want to add a keyword called @MyEnumA later, and don't want to break your code.Tasker
@GrahamLee Name clashes are not restricted to future additions to the language. Consider an enum named interface or end.Dishman
A
3

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);
Aleron answered 8/11, 2012 at 13:27 Comment(0)
G
2

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.

Gurge answered 8/11, 2012 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.