Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Boxing of primitives

Tags:

objective-c

I can't seem to figure out how to get Objective-c to auto box my primitives.

I assumed that i would be able to do the following

float foo = 12.5f;
NSNumber* bar;

bar = foo;

However i find that i have used to the more verbose method of

float foo = 12.5f;
NSNumber* bar;

bar = [NSNumber numberWithFloat:foo];

Am i doing it wrong or is this as good as it gets?

like image 201
Jonathan Avatar asked Mar 19 '10 12:03

Jonathan


People also ask

What is the major advantage of auto boxing?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

What is Auto boxing in Javascript?

Autoboxing happens automatically whenever we treat a primitive type like an object. In other words, whenever we try to .length on a string for example or toString a number, or get the value of a Boolean.

What is the difference between boxing and Autoboxing?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you. For instance, if you write in code: // list is a List<Integer> list.

Is Autoboxing also known as boxing?

The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing.


2 Answers

Unfortunately, Objective-C does not do auto-boxing or unboxing of primitive types to NSNumber. When put that way, it may be clear why: Objective-C has no concept of NSNumber, a class in the Cocoa Foundation framework. As a small superset of C, Objective-C doesn't have a "native" numeric object type--just the native C types.

Edit Aug 2012 As of Xcode 4.4 (and LLVM 4.0), you can now use some syntactic sugar to wrap numbers. Following your example, these "boxed expressions" now work:

float foo = 12.5f;
NSNumber* bar;

bar = @(foo);
bar = @12.5f;
like image 168
Barry Wark Avatar answered Sep 28 '22 17:09

Barry Wark


Clang 3.1 and Apple LLVM 4.0 (included in Xcode 4.4) support a new boxing feature: http://clang.llvm.org/docs/ObjectiveCLiterals.html#objc_boxed_expressions

You're now able to write:

NSNumber *bar = @(foo);

as well as:

NSNumber *bar = @12.5F;

So it just got a little better. :)

like image 35
nschum Avatar answered Sep 28 '22 17:09

nschum