歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Objective-C編程中的數字類型(NSInteger,NSUInteger,NSNumber)

Objective-C編程中的數字類型(NSInteger,NSUInteger,NSNumber)

日期:2017/3/1 9:35:21   编辑:Linux編程

在Objective-C中,我們可以使用c中的數字數據類型,int、float、long等。它們都是基本數據類型,而不是對象。也就是說,不能夠向它們發送消息。然後,有些時候需要將這些值作為對象使用。

NSInteger、NSUInteger

當你不知道程序運行哪種處理器架構時,你最好使用NSInteger,因為在有可能int在32位系統中只是int類型,而在64位系統,int可能變是long型。除非不得不使用int/long型,否則推薦使用NSInteger。

從上面的定義可以看出NSInteger/NSUInteger是一種動態定義的類型,在不同的設備,不同的架構,有可能是int類型,有可能是long類型。NSUInteger是無符號的,即沒有負數,NSInteger是有符號的。

NSNumber

有人說既然都有了NSInteger等這些基礎類型了為什麼還要有NSNumber?

NSNumber可以將基本數據類型包裝起來,形成一個對象,這樣就可以給其發送消息,裝入NSArray中等。

NSInteger intVal = 123;

NSNumber *numberVal = [NSNumber numberWithInteger:intVal];

NSMutableArray* array = [NSMutableArray array];

[array addObject:intVal]; //錯誤,intVal不是一個對象類型

[array addObject:numberVal]; //正確

Cocoa提供了NSNumber類來包裝(即以對象形式實現)基本數據類型。

+ (NSNumber*)numberWithChar: (char)value;+ (NSNumber*)numberWithInt: (int)value;+ (NSNumber*)numberWithDouble:(double)value;+ (NSNumber*)numberWithFloat: (float)value;+ (NSNumber*)numberWithBool: (BOOL) value;...

將基本類型數據封裝到NSNumber中後,就可以通過下面的實例方法重新獲取它:

- (char)charValue;- (int)intValue;- (float)floatValue;- (double)doubleValue;- (BOOL)boolValue;...

NSValue類

但是我們往往也會有這樣的需求,例如需要將CGPoint 或是CGRect這樣的結構存儲在集合中.一個NSValue對象是用來存儲一個C或者Objective-C數據的簡單容器。它可以保存任意類型的數 據,比如int,float,char,當然也可以是指pointers, structures, and object ids。NSValue類的目標就是允許以上數據類型的數據結構能夠被添加到集合裡.這種結構轉化為對象的方式,不就是java中的裝箱(boxing) 嗎?不過在Objective-C中稱為包裝(wraping),相反的,從對象中解出基本類型,稱為展開(unwraping),在java中叫拆箱 (unboxing).

NSNumber 繼承自NSObject,可使用compare、isEqual等消息。

NSNumber是NSValue的子類。NSValue可包裝任意類型值。

Objective-C中@property的所有屬性詳解 http://www.linuxidc.com/Linux/2014-03/97744.htm

Objective-C 和 Core Foundation 對象相互轉換的內存管理總結 http://www.linuxidc.com/Linux/2014-03/97626.htm

使用 Objective-C 一年後我對它的看法 http://www.linuxidc.com/Linux/2013-12/94309.htm

10個Objective-C基礎面試題,iOS面試必備 http://www.linuxidc.com/Linux/2013-07/87393.htm

Objective-C適用C數學函數 <math.h> http://www.linuxidc.com/Linux/2013-06/86215.htm

好學的 Objective-C 高清PDF http://www.linuxidc.com/Linux/2014-09/106226.htm

Copyright © Linux教程網 All Rights Reserved