6

I've been looking at autoboxing in Objective-C (here, for instance). Is there a new syntax for unboxing?

For instance, I want to do this but shorter:

NSArray *oneNumber = @[@1];
int one = ((NSNumber *)oneNumber[0]).intValue;

the second line's syntax is horrific. Is there any new language feature to deal with this?

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
  • 1
    Note that this is neither auto-boxing nor auto-unboxing. The `@...` syntax for scalars and collections is, like the dot syntax, compiler shorthand for a concrete method call. Autoboxing would imply that a bare scalar (`int x = 5;`) would be magically boxed when passed to a method that requires `NSNumber*`. (KVC's `valueForKey:` is auto-boxing / un-boxing, for example). – bbum Jan 15 '13 at 18:46
  • 1
    Thanks for that, @bbum. Correct to call them "object literals?" – Dan Rosenstark Jan 16 '13 at 15:03

2 Answers2

8
[oneNumber[0] intValue]

Sometimes the old ways are best.

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
  • I always forget that there are limits to the dot syntax. +1 great point – Dan Rosenstark Jan 15 '13 at 17:06
  • Provided you KNOW in advance that oneNumber[0] responds to intValue call. Else you crash. I agree, however about the "old ways". Too much of a "good thing" may sometimes... – Motti Shneor Dec 26 '22 at 10:15
0

Another way to go is to stay in the object world. For instance:

NSNumber *one = @1;
NSArray *oneNumber = @[one];
one = oneNumber[0];
NSLog(@"one %@", one);
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421