IOS 學習筆記 2015-03-20 OC-數實值型別,2015-03-20oc-
一 定義 在Objective-C中,我們可以使用c中的數字資料類型,int、float、long等。它們都是基礎資料型別 (Elementary Data Type),而不是對象。也就是說,不能夠向它們發送訊息。然後,有些時候需要將這些值作為對象使用。二 關鍵字1 NSInteger int 封裝類型 A 當你不知道程式運行哪種處理器架構時,你最好使用NSInteger,因為在有可能int在32位系統中只是int類型,而在64位系統,int可能變是long型。除非不得不使用int/long型,否則推薦使用NSInteger。B 從上面的定義可以看出NSInteger/NSUInteger是一種動態定義的類型,在不同的裝置,不同的架構,有可能是int類型,有可能是long類型。2 NSUInteger 是無符號的,即沒有負數,NSInteger是有符號的。 3 NSNumber A 專門用來裝基礎類型的對象,把整型、單精確度、雙精確度、字元型等基礎類型儲存為對象B NSNumber可以將基礎資料型別 (Elementary Data Type)封裝起來,形成一個對象,這樣就可以給其發送訊息,裝入NSArray中C NSInteger和普通資料類型是不能被封裝到數組中的
//// main.m// OC-NSNumber//// Created by wangtouwang on 15/3/20.// Copyright (c) 2015年 wangtouwang. All rights reserved.//#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... //建立 NSNumber *_n1 = [[NSNumber alloc] initWithInt:9]; NSNumber *_n2 = [[NSNumber alloc] initWithFloat:8.1f]; NSNumber *_n3 = [[NSNumber alloc] initWithDouble:8.1]; NSNumber *_n4 = [[NSNumber alloc] initWithChar:'A']; NSLog(@"N1=%@ N2=%@ N3=%@ n4=%@",_n1,_n2,_n3,_n4); //還原 // 轉換為int int n1 = [_n1 intValue]; //轉換為double double n3 = [_n3 doubleValue]; //轉換為 float float n2 = [_n2 floatValue]; // 轉換為 char char n4 = [_n4 charValue]; NSLog(@"N1=%i N2=%f N3=%f n4=%c",n1,n2,n3,n4); //比較是否相等 NSLog(@"%@",[_n3 isEqualToNumber:_n2]?@"==":@"!="); //比較大小 NSLog(@"%ld",[_n1 compare:_n2]); //數組可以增加NSNumber對象 NSMutableArray *_array2 = [[NSMutableArray alloc] initWithObjects:_n1,_n2,_n3,_n4, nil]; NSInteger INDEX= 12; //嘗試用數組增加NSInteger對象 結果報錯了,說明文法不支援// NSMutableArray *_array1 = [[NSMutableArray alloc] initWithObjects:_n1,_n2,_n3,_n4, INDEX,nil];// NSLog(@"%lu",[_array1 count]); } return 0;}