美文网首页
0926-const,static,extern关键字

0926-const,static,extern关键字

作者: JC_Wang | 来源:发表于2016-09-26 10:12 被阅读9次

1、用法

  • const: 被const修饰的变量是只读的,不可更改。推荐使用const来替代宏定义,宏定义不会报错
  • static: 延长变量的生命周期,程序结束才会销毁。在同一作用域或文件中,只被初始化一次
  • extern:生明一个全局变量,不能定义变量。现在当前文件中查找全局变量,如果没有,再去其他文件中查找

2、经典使用场景

1、static和const的组合使用,代替宏定义全局变量

#pragma mark - 全局数值的变量
#pragma mark -

static const NSTimeInterval ani_time = 5;

- (IBAction)ShowAction:(id)sender {
    
    UIView *view = [[UIView alloc]initWithFrame:self.view.bounds];
    view.backgroundColor = [UIColor redColor];
    //包含了NSTimeInterval的类型信息,有助于开发文档的编写和后续的维护,并且不可修改,相同名字会报错,全局有效
  
    [UIView animateWithDuration:ani_time animations:^{
        
        [self.view addSubview:view];
    }];
    
}

2、extern和const的组合使用,供外界使用且只读

.h

@interface Money : NSObject

//扩展,只读的字符串变量定义
extern NSString *const money;

@end

.m

#import "Money.h"

NSString *const money = @"10元";

@implementation Money

@end

相关文章

网友评论

      本文标题:0926-const,static,extern关键字

      本文链接:https://www.haomeiwen.com/subject/dycqyttx.html