自动装箱原语 [英] Auto Boxing of primitives

查看:67
本文介绍了自动装箱原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚如何使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?

推荐答案

不幸的是,Objective-C不会将原始类型的自动装箱或拆箱到NSNumber.如果这样说,可能会很清楚为什么:Objective-C没有可可基金会框架中的类NSNumber的概念.作为C的一个小超集,Objective-C没有本机"数字对象类型-只是本机C类型.

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.

编辑2012年8月 从Xcode 4.4(和LLVM 4.0)开始,您现在可以使用一些语法糖来包装数字.按照您的示例,这些框式表达式"现在可以工作:

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;

这篇关于自动装箱原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆