tags:

views:

164

answers:

2

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?

+2  A: 

This is as good as is gets.

KennyTM
+4  A: 

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.

Barry Wark
I might say "inconveniently" rather than "unfortunately". Languages with auto-(un)boxing are not free of problems — in fact, many of them are hard to spot and can cause strange issues. For example, Effective Java and Java Puzzlers devote quite a few pages to clearing up confusion about how numbers act unexpectedly in various situations. It would be quite convenient to have auto-boxing, but adding it to the language itself (as you point out) would be non-trivial, and likely fraught with hidden perils.
Quinn Taylor
@Quinn Absolutely. I was really trying to make the point that Objective-C couldn't easily do autoboxing, not trying to make a judgement about the situation. Any of us that have "enjoyed" Java's autoboxing knows it's not a free lunch. I've heard C#'s is better, but don't have personal experience with which to judge.
Barry Wark