views:

39

answers:

1

I love the shorthand handling of string literals in Objective C with the @"string" notation. Is there any way to get similar behavior with NSNumbers? I deal with numbers more and it's so tedious having [NSNumber numberWithWhatever:] calls everywhere. Even creating a macro would work, but my knowledge of how best to do that is limited.

+4  A: 

I'm using a macro like

#define N(x) [NSNumber numberWithInt: x]

wich leads to code like

[N(123) intValue];

update:

One should be aware of the CPU and memory consumption of such a macro. While the @"…" strings are static compiler generated strings of the constant string class (depends on foundation maybe NSConstantString in Cocoa?) the macros create code which is evaluated at runtime and therefore create a new object every time they are called.

Tilo Prütz
Nice one, that'll work. Thanks!
rob5408
Slight improvement: `#define N(x) [NSDecimalNumber decimalNumberWithString: @"" #x]`. Will allow you to do things like `N(1.4)` or `N(1E09)`
JeremyP
Yes, but isn't it significant slower? I'm using an `F(x)` macro for floating points which invokes `[NSNumber numberWithDouble: x]`.
Tilo Prütz