美文网首页
iOS - extern作用

iOS - extern作用

作者: aven_kang | 来源:发表于2022-06-09 23:36 被阅读0次

    extern用于变量的声明,告诉编译器:已经存在一个全局变量,但是不在当前的编译单元内,需要连接的时候在其他编译单元中寻找。

    在开发中,我们经常会定一个文件,用于作用于各种统一的名称,比如一些通知的名称,就不用每次都手写通知中心发出的通知,比如@"xxxxNotification",这样不仅容易写错,也不易于记忆,但是我们怎么解决这个问题呢,如下图我们构造一下


    image.png

    .h文件

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface InterfaceHeader : NSObject
    
    extern NSString * const headerNotification;
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    .m文件

    #import "InterfaceHeader.h"
    
    NSString * const headerNotification = @"headerNotification"
    

    然后我们在ViewController中的使用

    #import "ViewController.h"
    #import "InterfaceHeader.h"
    
    
    @interface ViewController ()
    
    
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(testAction) name:headerNotification object:nil];
        
        
    }
    

    在viewController中我们看到headerNotification是直接被使用了,这样就有利于规范化

    相关文章

      网友评论

          本文标题:iOS - extern作用

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