美文网首页
iOS开发之static、extern、const和define

iOS开发之static、extern、const和define

作者: 小羊爱学习 | 来源:发表于2019-03-06 17:39 被阅读0次

关于define和const的区别在之前的文章中已经解释过,本篇文章主要是把这几个统一整理一下。

一、define:

预编译,简单的字符串替换,没有类型检查,可以预编译表达式,也可以定义常量

#define SCREEN_RECT ([UIScreen mainScreen].bounds)

#ifdef DEBUG
#define TLLog(...) NSLog(__VA_ARGS__)
#else
#define TLLog(...)
#endif

#define navtitlefont 17

使用:一般在pch文件中定义一些全局的宏表达式

二:const:

编译时刻,有类型检查,onst仅仅用来修饰右边的变量,被const修饰的变量是只读的。

onst CGFloat itemWidth = 60.0;

int  const  *p   //  *p只读 ;p变量

int  * const  p  // *p变量 ; p只读

const  int   * const p //p和*p都只读

int  const  * const  p   //p和*p都只读

使用:一般用在文件中来定义一些不可修改的常量

三:static:

修饰局部变量:

1.不可以改变局部变量的作用域,因而只能在代码块内部使用,但是可延长局部变量的生命周期,程序结束才会销毁。

2.当static关键字修饰局部变量时,该局部变量只会初始化一次,在系统中只有一份内存

修饰全局变量

1.修改全局变量的作用域,作用域仅限于当前文件,外部类不可以访问到该变量

2.避免重复定义全局变量

static LightBlueManger *_manger = nil;

@implementation LightBlueManger{
    FMDatabaseQueue *_dataBase;//数据库管理的对象
}
+ (LightBlueManger *)shareManger{
    
    //线程安全的单例
    static dispatch_once_t Token;
    dispatch_once(&Token,^{
        if(_manger == nil) {
            _manger = [[LightBlueManger alloc] init];
        }
        
    });
    
    return _manger;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier=@"cellforpersonmanage";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
//        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    cell.textLabel.text = self.dataSource[indexPath.row][@"healUserName"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"共计%ld个",[self.dataSource[indexPath.row][@"fileCount"] integerValue]];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    return cell;
    
}

使用:单例创建、UITableViewCell的identifier标识等

四:extern:

作用是声明外部全局变量。这里需要特别注意extern只能声明,不能用于实现。
使用:在开发中,我们通常会单独抽一个类来管理一些全局的变量或常量,通常搞一个GlobeConst文件,里面专门定义全局常量或常量
我们可以在.h文件中extern声明一些全局的常量

//声明一些全局常量

extern NSString * const name;

extern NSInteger const age;

然后在.m文件中去实现

#import <Foundation/Foundation.h>

//实现

NSString * const name = @"贾小羊";

NSInteger const age = 18;

这样,只要导入头文件,就可以全局的使用定义的变量或常量。

五:组合使用:

static和const组合:开发中经常用到static和const一起使用的情况,如定义一个只能在当前文件访问的全局常量

    static  类型   const   常量名  = 初始化值

    例如:static NSString * const test = @"abc";

extern与const组合:只需要定义一份全局常量或变量,多个文件共享。例子如四。

对于全局常量或变量的定义,一般我们在pch文件中用#define去定义一些全局的宏表达式,因为只有#define才可以定义表达式。用extern与const组合在GlobeConst文件中定义一些不需要表达式的全局常量。

相关文章

网友评论

      本文标题:iOS开发之static、extern、const和define

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