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?
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.
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.
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.
The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing.
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;
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With