NSNumber与NSArray的原始int [英] NSNumber vs. primitive int for NSArray

查看:103
本文介绍了NSNumber与NSArray的原始int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用适用于Mac OSX的第四版Cocoa编程来学习Objective-C/Cocoa.对于这个基本问题,我深表歉意,但我是真正需要了解一切内容以便对我有意义的人之一,而本书并不总是针对我的需要.我已经学习了C ++的基础知识,现在我正在学习Obj-C,所以这是我的背景.这是我正在学习的代码片段...

I am learning Objective-C/Cocoa using the 4th edition of Cocoa Programming for Mac OSX. I apologize for the basic question but I'm one of those people that really need to understand the insides of everything in order for it to make sense to me and this book doesn't always do that to my needs. I've already picked up the basics of C++ and now I'm learning Obj-C so that is my background. This is a snippet of code that I'm learning...

for (i= 0; i < 10; i++) {
    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i * 3)];
    [array addObject:newNumber];
}

我的问题是,为什么要创建NSNumber实例以添加到数组中,而不仅仅是单个整数变量.似乎可以避免每个循环创建一个新实例只是额外的开销.但是我敢肯定,作者知道自己在做什么,这是有原因的,有人可以解释一下吗?

My question is why would you create instances of NSNumber to add to the array instead of just a single integer variable. It seems like it is just extra overhead creating a new instance each loop that could be avoided. But I'm sure the authors know what they are doing and there is a reason for it, could someone please explain?

推荐答案

NSArray只能保存对象,而不能保存原始类型. NSNumber和NSValue用于将原始类型包装在对象中,因此它们可以存储在基础集合中,例如NSArray,NSDictionary和NSSet(及其可变/有序对应物)中.正如彼得·霍西(Peter Hosey)在评论中指出的:

NSArray can only hold objects, not primitive types. NSNumber and NSValue are used to wrap primitive types in objects, so they can be stored in foundation collections like NSArray, NSDictionary, and NSSet (and their mutable / ordered counterparts). As Peter Hosey points out in the comments:

通常的术语是装箱"(如将它们装箱),反之(从装箱对象中提取原始值)则是取消装箱.

The common term for this is "boxing" (as in boxing them up), and the inverse — extracting the primitive value from a box object — is unboxing.

这篇关于NSNumber与NSArray的原始int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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