01-咱們通常把經常使用的字符串、基本變量定義成宏面試
02-蘋果一直推薦咱們使用const、而不是宏swift
03-並且在swift中,蘋果已經取締了使用宏,不能再使用了函數
1:宏 與 const 的區別?spa
誤解:有一些博客說:大量使用宏,讓使內存暴增?指針
解釋:其實這是錯誤的說法,大量使用宏,其實並不會使內存暴增,由於你大量使用的這個宏都是同一個地址,它只會讓你的預編譯時間增大而已,讓內存暴增是錯誤的說法code
// const有編譯檢查內存
#define XJAppName @"魔多" 123 編譯不會檢查 CGFloat const a = 3; 123 編譯檢查會顯示錯誤
// 宏能夠定義方法或者函數字符串
#define XJUserDefaultKey [NSUserDefaults standardUserDefaults] const XJUserDefaultKey1 = [NSUserDefaults standardUserDefaults]; [XJUserDefaultKey setObject:@"123" forKey:@"name"]; [XJUserDefaultKey objectForKey:@"name"];
2:const的基本使用?博客
// 面試題: int * const p1; // p1:只讀 *p1:可修改(變量) int const * p2; // p2:可修改(變量) *p2:只讀 const int * p3; // p3:可修改(變量) *p3:只讀 const int * const p4; // p4:只讀 *p4:只讀 int const * const p5; // p5:只讀 *p5:只讀
// 正確 int a = 3; a = 5; // 錯誤(只讀){這兩種寫法同樣} //int const b = 3; const int b = 3; //b = 5; // 修飾指針變量 /* int c = 3; int *p = &c; // 修改c的值(地址修改) c = 5; *p = 8; */ /* int c = 3; int const *p = &c; // 修改c的值(地址修改) c = 5; *p = 8; */
3:const的使用場景?it
如:修飾全局變量
#import "ViewController.h" //#define XJNameKey @"123" // const修飾右邊的XJNameKey不能修改,只讀 NSString * const XJNameKey = @"123"; @interface ViewController () @end /** const的使用場景 * 1: 修飾全局變量 => 全局只讀變量 * 2: 修飾方法中參數 */ @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[NSUserDefaults standardUserDefaults] setObject:@"123" forKey:XJNameKey]; //XJNameKey = @"321"; // 錯誤,const修飾了不能修改了, } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; [[NSUserDefaults standardUserDefaults] objectForKey:XJNameKey]; }
如:修飾方法中參數:
- (void)viewDidLoad { [super viewDidLoad]; [[NSUserDefaults standardUserDefaults] setObject:@"123" forKey:XJNameKey]; //XJNameKey = @"321"; // 錯誤,const修飾了不能修改了, int a = 0; [self test:&a]; } - (void)test:(int const *)a { *a = 3; // 錯誤不能修改 } - (void)test:(int *)a { *a = 3; // 能夠能修改 }
意見反饋郵件:1415429879@qq.com 歡迎大家的閱讀和讚揚、謝謝!