const 常量修饰符

2019-01-15  本文已影响19人  zone1026

const 定义一个常量,常类型的变量或对象的值是不能被修改的,类似于只读属性。使用场景介绍:

1、修饰基本数据类型常量

书写格式:const 数据类型 符号常变量 = 数值

 const CGFloat kNormalImgWidth = 20;
2、修饰指针常量,存储的指针可变,存储的值不可变

书写格式:数据类型 *const 指针常量命名 = 数据

 #import <UIKit/UIKit.h>

NSString * const tips = @"111";

@interface ViewController : UIViewController
@end
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    extern NSString *tips;
    NSLog(@"%@",tips); // 输出 111
    tips = @"222";
    NSLog(@"%@",tips);// 输出 222
    return YES;
}
#import "ViewController.h"

@interface ViewController () 
@end

@implementation ViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"%@",tips); // 输出 111
}
3、修饰常量指针,存储的值可变,存储的指针不可变

书写格式:const 数据类型 *指针常量命名 = 数据,这种使用方式存在隐患,常量的值有可能被修改,如果常量被修改,就违背了我们使用常量的初衷,所以这种方式不推荐使用

 #import <UIKit/UIKit.h>

const NSString * tips = @"111";

@interface ViewController : UIViewController
@end
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    extern NSString *tips;
    NSLog(@"%@",tips); // 输出 111
    tips = @"222";
    NSLog(@"%@",tips);// 输出 222
    return YES;
}
#import "ViewController.h"

@interface ViewController () 
@end

@implementation ViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"%@",tips); // 输出 222
}

与宏定义的区别

#define kScreenWidth [UIScreen mainScreen].bounds.size.width

#define 这么写是没问题的,因为宏定义是代码的替代,在编译阶段会逐一替换,但是const这么写就有问题了,比如:

const CGFloat kScreenW = [UIScreen mainScreen].bounds.size.width;

这是就是提示 “Initializer element is not a compile-time constant”,const修饰的变量值是不可变的,相当于readonly

const CGFloat normalW = 10.0f;
#define kWXDropClose @"Open1"

@interface AppDelegate : UIResponder <UIApplicationDelegate>
#define kWXDropClose @"Open1"
const CGFloat normalW = 10.0f;

@interface ViewController : UIViewController
提示有重复的命名

const 作用域说明

1、全局常量:不管定义在任何类文件中,其他类文件都可以访问,并且不用引入类文件,修饰符extern,默认的可以不写

 extern NSString * const tips = @"提示信息";

NSString * const newTips = @"新的提示信息";

2、静态常量:使用时需要引入类文件,并且必须在.h文件中,否则找不到常量的定义,修饰符static

 static NSString * const tips = @"提示信息";
上一篇 下一篇

猜你喜欢

热点阅读