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
2010-09-20 12:47:47
Nice one, that'll work. Thanks!
rob5408
2010-09-20 13:00:01
Slight improvement: `#define N(x) [NSDecimalNumber decimalNumberWithString: @"" #x]`. Will allow you to do things like `N(1.4)` or `N(1E09)`
JeremyP
2010-09-20 13:08:40
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
2010-09-20 13:17:12