標籤:
NSNumber: 是OC中處理數位一個類
NSValue是NSNumber的子類
如何處理:
把int,float,double 封裝成一個對象
使用NSNumber的好處:
可以把基礎資料型別 (Elementary Data Type)的資料,儲存到數組或字典中
// 定義基礎資料型別 (Elementary Data Type) int a = 10; float b = 2.2f; double d = 1.22; int x = 100; // int 封裝成 NSNumber NSNumber *intObj = [NSNumber numberWithInt:a]; NSMutableArray *array = [NSMutableArray arrayWithObjects: intObj, nil]; // float 封裝成 NSNumber NSNumber *floatObj = [NSNumber numberWithFloat:b]; // 把對象添加到數組中 [array addObject:floatObj]; // double 封裝成 NSNumber NSNumber *doubleObj = [NSNumber numberWithDouble:d]; // 把對象添加到數組中 [array addObject:doubleObj]; // @數值,把數值封裝成對象,快速簡單的方法 [array addObject:@(x)]; NSLog(@"%@",array); // 數組的第一個元素和第二個元素相加 NSNumber *n1 = array[0]; // 取出第0位元素 int a1 = [n1 intValue]; NSNumber *n2 = array[1]; // 取出第1位元素 float a2 = [n2 floatValue]; //a1 = a1+a2; // 簡潔 a1 = [array[0] intValue] +[array[1] floatValue]; NSLog(@"%d",a1);
NSValue:主要是用來把指標,CGRect結構體等封裝成OC對象,以便儲存
CGPoint p1 = CGPointMake(3, 5); CGRect r1 = CGRectMake(0, 3, 5, 9); NSMutableArray *arr = [NSMutableArray array]; // p1封裝成 obj NSValue *pointValue = [NSValue valueWithPoint:p1]; // 把對象存到數組中 [arr addObject:pointValue]; // 把r1 封裝成 NSValue對象 [arr addObject:[NSValue valueWithRect:r1]]; NSLog(@"%@",arr); // 取出r1 的值 NSValue *r1Value = [arr lastObject]; NSRect r2 = [r1Value rectValue]; NSLog(@"%@", NSStringFromRect(r2));
封裝struct
// 定義日期結構體typedef struct Date{ int year; int month; int day; } MyDate;int main(int argc, const char * argv[]) { @autoreleasepool { // 年—月-日 MyDate nyr = {2015, 9, 11}; // @encode(MyDate)作用,把MyDate類型產生一個常量字串描述 NSValue *val = [NSValue valueWithBytes:&nyr objCType:@encode(MyDate)]; // 定義一個數組,把val存到數組中 NSMutableArray *arr = [NSMutableArray arrayWithObject:val]; /* 從數組中取出來NSValue對象 從對象中,取出結構體變數的值 傳入一個結構體變數的地址 */ MyDate tmd; [val getValue:&tmd]; NSLog(@"%d, %d. %d",tmd.year, tmd.month, tmd.day);
Objective-C( Foundation架構 一 NSNumber(NSValue))