如果我能写:
test_string = [[NSString alloc] init]; and
test_date = [[NSDate alloc] init];
为什么,如果只是出于一致性的原因,我不能写:
test_integer = [[NSInteger alloc] init]; or
test_decimal = [[NSDecimal alloc] init];
以及如何设置它们?
我建议必读数字和值编程指南。
它将帮助您从这一切开始,但请记住,通常使用标量值(C 标准值类型:int、float、long 等)会更容易,除非您想具体使用它们(将值存储在NSArray,在微积分上具有最高的精度并避免奇怪的浮点舍入等)
您的前两个示例是真实对象,因此必须使用alloc
/ init
(或简写形式new
.
AnNSInteger
只是int
or的 typedef long
,具体取决于平台,也就是说,它只是int
or的另一个名称long
。这些都是所谓的原始类型。它们不是真实的物体,而是更简单的东西。它们没有任何方法、iVar 等 - 事实上,它们实际上只是数字,而表示数字的对象(例如 an [NSNumber numberWithInt:1]
)要多得多。
当速度和内存效率很重要时,会使用原始类型,而整数的使用如此频繁以至于这些考虑在这里很重要。顺便说一句,Smalltalk(启发了 Objective-C 语法和对象模型的语言)没有原始类型。甚至整数,甚至布尔值都是对象。这更加一致(并且在某些方面更强大),但它是使 Smalltalk 在 70 年代和 80 年代初期变得相当缓慢的因素之一。
NSDecimal
is also not an object, but a struct. A struct is essentially a list of named primitive values. Other often-used structs in Objective-C where this might be more obvious are CGPoint
(A struct containing two floats, x and y), CGSize
(again a struct containing two floats, this time called width and height), CGRect
(a struct containing a CGPoint
struct named origin, and a CGSize
struct named size).