OC:static 、 extern 和 const

2019-04-03  本文已影响0人  春暖花已开
说明 时间
首次发布 2019年04月03日
最近更新 2019年04月09日
static
- (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>释放了

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
    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'
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";
上一篇 下一篇

猜你喜欢

热点阅读