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 欢迎大家的阅读和赞扬、谢谢!