OC:static 、 extern 和 const

说明 时间
首次发布 2019年04月03日
最近更新 2019年04月09日
static
  • 1、修饰局部变量的时候,该局部变量只会 初始化一次,且 内存中的地址不变,和 延长局部变量的生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
   
    static NSInteger count = 0;
    count++;
    NSLog(@"打印:%ld, 地址:%p", count, &count);
}

输出如下(忽略部分无用内容):

2019-04-03 打印:1, 地址:0x1021d1510
2019-04-03 <FourthViewController: 0x7ffd716082d0>释放了
2019-04-03 打印:2, 地址:0x1021d1510
2019-04-03 <FourthViewController: 0x7ffd71403eb0>释放了
2019-04-03 打印:3, 地址:0x1021d1510
2019-04-03 <FourthViewController: 0x7ffd7530d200>释放了
  • 2、使全局变量的作用域只限定在本类里(默认情况下,全局变量在整个程序中是可以被访问,即:全局变量的作用域是整个项目文件)。

extern:访问全局变量,只需要定义一份全局变量,多个文件共享,与 const 一块使用。

一般使用场景:写一个全局变量的类 GlobalConst,GlobalConst.h声明,GlobalConst.m赋值。如:

// GlobalConst.h
#import <Foundation/Foundation.h>
extern NSString *const noticeName;

// GlobalConst.m
#import "GlobalConst.h"
NSString *const noticeName = @"noticeName";

如系统的方式:

// .h
UIKIT_EXTERN NSNotificationName const UIApplicationDidFinishLaunchingNotification;
UIKIT_EXTERN NSNotificationName const UIApplicationDidBecomeActiveNotification;
UIKIT_EXTERN NSNotificationName const UIApplicationWillResignActiveNotification;

const
  • 1、修饰基本数据类型: const intint const 是一样的。编译器都认为是 int const 类型。
    const int count = 10;
    int const num = 20;
//    count = 10; //Cannot assign to variable 'count' with const-qualified type 'const int'
//    num = 20;  //Cannot assign to variable 'num' with const-qualified type 'const int'
  • 2、修饰指针类型: 星号以及星号之后的内容,只修饰右侧的一个变量。
NSString *const a = @"a";
//    a = @"b"; // ❌ Cannot assign to variable 'a' with const-qualified type 'NSString *const __strong'
    
const NSString *b = @"b";
// *b 不可变,Read-only variable is not assignable
b = @"c";

NSString const *c = @"c";
c = @"dd";
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容