美文网首页
OC:static 、 extern 和 const

OC:static 、 extern 和 const

作者: 春暖花已开 | 来源:发表于2019-04-03 23:06 被阅读0次
说明 时间
首次发布 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";

相关文章

网友评论

      本文标题:OC:static 、 extern 和 const

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