在 Objective-C 的 Foundation 框架中,NSNumber 是一個不可不認識的基礎類。由於 Objective-C 的集合類(如 NSArray、NSDictionary、NSSet)只能存放物件,而無法直接容納 int、float、double、BOOL 等基本型別,因此我們需要透過 NSNumber 將這些純量值包裝成物件,才能放進集合裡進行管理。
NSNumber 繼承自 NSValue,並遵循 NSCopying、NSSecureCoding 等協定。它屬於 Foundation 框架,自 iOS 2.0 起便已提供,主要宣告於 NSValue.h 與 NSDecimalNumber.h 中。
你可以透過一組以 numberWith 開頭的便利建構子(Factory Method),快速地把各種型別的值轉換為 NSNumber:
+ numberWithBool:+ numberWithChar:+ numberWithDouble:+ numberWithFloat:+ numberWithInt:+ numberWithInteger:+ numberWithLong:+ numberWithLongLong:+ numberWithShort:+ numberWithUnsignedChar:+ numberWithUnsignedInt:+ numberWithUnsignedInteger:+ numberWithUnsignedLong:+ numberWithUnsignedLongLong:+ numberWithUnsignedShort:除了便利建構子之外,也可以使用對應的 initWith 初始化方法來建立物件:
- initWithBool:- initWithChar:- initWithDouble:- initWithFloat:- initWithInt:- initWithInteger:- initWithLong:- initWithLongLong:- initWithShort:- initWithUnsignedChar:- initWithUnsignedInt:- initWithUnsignedInteger:- initWithUnsignedLong:- initWithUnsignedLongLong:- initWithUnsignedShort:當你取得一個 NSNumber 物件後,可以透過下列存取器把值取回為對應的純量型別:
- boolValue - charValue - decimalValue- doubleValue - floatValue - intValue- integerValue - longLongValue - longValue- shortValue - unsignedCharValue - unsignedIntegerValue- unsignedIntValue - unsignedLongLongValue - unsignedLongValue- unsignedShortValue- descriptionWithLocale:- stringValue- compare:- isEqualToNumber:- objCType掌握以上這些方法,你就能在需要「以物件形式儲存數字」的情境中游刃有餘,例如在 JSON 解析、集合操作或與 Core Data 互動時,NSNumber 幾乎無所不在。
本文內容整理自 Apple 官方類別參考文件(更新於 2013-12-16)。Apple Inc. 版權所有。