C 基本類型(int、float、BOOL 等)非對象,無法存入集合(NSArray、NSDictionary)、無法發送消息。NSNumber 為其提供對象包裝器。
NSNumber *num1 = [[NSNumber alloc] initWithInt:10];
NSNumber *num2 = [[NSNumber alloc] initWithFloat:10.8f];
NSNumber *num3 = [[NSNumber alloc] initWithBool:YES];
// 完整列表見下表
NSNumber *num1 = [NSNumber numberWithInt:10];
NSNumber *num2 = [NSNumber numberWithFloat:10.8f];
NSNumber *num3 = [NSNumber numberWithBool:YES];
// 推薦:語法簡潔,自動管理內存(ARC 環境下)
int i = [num1 intValue];
float f = [num2 floatValue];
BOOL b = [num3 boolValue];
// 完整列表見下表
| 基本類型 | 裝箱 (initWith...) | 裝箱 (numberWith...) | 拆箱 (...Value) |
|---|---|---|---|
| char | initWithChar: | numberWithChar: | charValue |
| unsigned char | initWithUnsignedChar: | numberWithUnsignedChar: | unsignedCharValue |
| short | initWithShort: | numberWithShort: | shortValue |
| unsigned short | initWithUnsignedShort: | numberWithUnsignedShort: | unsignedShortValue |
| int | initWithInt: | numberWithInt: | intValue |
| unsigned int | initWithUnsignedInt: | numberWithUnsignedInt: | unsignedIntValue |
| long | initWithLong: | numberWithLong: | longValue |
| unsigned long | initWithUnsignedLong: | numberWithUnsignedLong: | unsignedLongValue |
| long long | initWithLongLong: | numberWithLongLong: | longLongValue |
| unsigned long long | initWithUnsignedLongLong: | numberWithUnsignedLongLong: | unsignedLongLongValue |
| float | initWithFloat: | numberWithFloat: | floatValue |
| double | initWithDouble: | numberWithDouble: | doubleValue |
| BOOL | initWithBool: | numberWithBool: | boolValue |
| NSInteger | initWithInteger: | numberWithInteger: | integerValue |
| NSUInteger | initWithUnsignedInteger: | numberWithUnsignedInteger: | unsignedIntegerValue |
#import
int main() {
@autoreleasepool {
// 創建
NSNumber *month = [NSNumber numberWithInt:10];
NSNumber *length = [NSNumber numberWithFloat:10.8f];
NSLog(@"month = %@", month); // 輸出: 10
NSLog(@"length = %@", length); // 輸出: 10.8
// 拆箱
int m = [month intValue];
float l = [length floatValue];
NSLog(@"month = %d", m); // 10
NSLog(@"length = %.1f", l); // 10.8
}
return 0;
}
[NSNumber numberWithInt:42].stringValue → @"42"[num1 compare:num2] 返回 NSComparisonResult@42、@3.14f、@YES 等價於 [NSNumber numberWith...]@(5) == @(5) 可能為 YESNSValue 用於包裝結構體(CGRect、CGPoint 等)