static/extern&const

//const仅仅用来修饰右边的变量(基本数据变量p,指针变量*p)
static NSString *const keyA = @"keyA";
static NSString const *keyB = @"keyB";
static const NSString *keyC = @"keyC";
static const NSInteger numberA = 1;
static NSInteger const numberB = 1;
//keyA只读  keyB/keyC可变  numberA/numberB只读

 extern的用法

我在ViewController.h中声明了一个全局变量TestA

#import <UIKit/UIKit.h>
//前面加不加extern都是一样的 因为默认是添加extern NSString *const testA; @interface ViewController : UIViewController @end

在ViewController.m文件中赋值

#import "ViewController.h"
NSString * const testA = @"testA";
@interface ViewController ()
@end

然后如果我想在另外的文件中使用testA,例如在testViewController中。

只需要在testViewController中重新声明一下就可以了 

#import <UIKit/UIKit.h>

extern NSString * const testA;

@interface TestViewController : UIViewController

@end

这里会有一个疑问,我见大多数三方库,比如MJRefresh中,虽然也这样声明了变量,但是用的时候还是导入了声明变量时的头文件。。。

比如在MJExtensionConst中声明了一堆只读全局变量,但是在MJPropertyType文件中使用的时候还是导入了MJExtensionconst.h文件。

那这样是不是就有点多此一举了呢,直接使用static修饰不就可以了吗,还是说我理解extern有误。

猜你喜欢

转载自www.cnblogs.com/wycstudy/p/9229629.html