Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@"" string type literals for NSNumber

Tags:

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.

like image 951
rob5408 Avatar asked Sep 20 '10 12:09

rob5408


3 Answers

Since nobody has mentioned this... If you need to wrap a value in an NSNumber, the NSNumber literal syntax is as follows.

int val = 13;
NSNumber *numVal = @(val);
like image 171
Adam Lockhart Avatar answered Sep 24 '22 20:09

Adam Lockhart


As of Clang v3.1 you can now use Objective-C literals.

NSNumber *fortyTwo = @42;             // equivalent to [NSNumber numberWithInt:42]
NSNumber *fortyTwoUnsigned = @42U;    // equivalent to [NSNumber numberWithUnsignedInt:42U]
NSNumber *fortyTwoLong = @42L;        // equivalent to [NSNumber numberWithLong:42L]
NSNumber *fortyTwoLongLong = @42LL;   // equivalent to [NSNumber numberWithLongLong:42LL]

So, answering your specific question:

[Tyler setArms:[[[NSNumber alloc] initWithInt:1] autorelease]];

Can now be written as:

[Tyler setArms:@1];

There are also literals for arrays and dictionaries, but they are beyond the scope of this question.

To take advantage of literals in Xcode you'll need at least version 4.4 -- this comes with Apple's LLVM 4.0 compiler.

like image 31
Richard Stelling Avatar answered Sep 24 '22 20:09

Richard Stelling


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.

like image 9
Tilo Prütz Avatar answered Sep 23 '22 20:09

Tilo Prütz