Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber Literals

I am very new to Objective-C. I know C and C++ but Objective-C has quite the learning curve. Anyway, is there a shorter way (possibly by some kind of NSNumber literal if such exists) to write the following:

[Tyler setArms:[[[NSNumber alloc] autorelease] initWithInt:1]];
like image 985
Tyler Crompton Avatar asked Nov 28 '22 07:11

Tyler Crompton


2 Answers

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] autorelease] initWithInt:1]];

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 (at the time of writing this is a preview only).

NB: LLVM is an open source project so none of this is subject to Apple's NDA.

like image 167
Richard Stelling Avatar answered Dec 10 '22 22:12

Richard Stelling


Yes, just use one of the many helper functions such as numberWithInt::

[Tyler setArms:[NSNumber numberWithInt:1]];

The expression [NSNumber numberWithInt:1] is equivalent to [[[NSNumber alloc] initWithInt:1] autorelease], which is equivalent to [[[NSNumber alloc] autorelease] initWithInt:1]. The latter expression is extremely uncommon.

like image 43
Adam Rosenfield Avatar answered Dec 10 '22 23:12

Adam Rosenfield