美文网首页
iOS 开发 -《Effective Objective-C 2

iOS 开发 -《Effective Objective-C 2

作者: 错肩期盼 | 来源:发表于2018-09-26 14:04 被阅读44次

前言

主要记录下阅读此书中遇到的一些比较值得记录的东西。


一. const,static,extern的使用方法

  1. const修饰的变量为常量,即不可修改,是只读的。
const NSInteger a = 5; // a 不可被修改
NSInteger const a = 5; //  a 不可被修改
NSString const *str = @"hello world"; // const 修饰的变量是 *str 所以可以修改 str 所指向的地址,不能修改 *str 具体的内容
NSString * const str = @"hello world"; // const 修饰的变量是 str 所以可以修改 *str 具体的内容,不能修改 str 所指向的地址

2.static

修饰局部变量:
    1. 延长局部变量的生命周期,程序结束才会销毁。
  • 2.局部变量只会生成一份内存,只会初始化一次。

  • 3.改变局部变量的作用域。

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //声明一个局部变量i
    int i = 0;
    //每次点击view来到这个方法时让i自增
    i ++;
    //打印结果
    NSLog(@"i=%d",i);
}

输入日志如下

2018-09-26 12:58:48.290 BaseRACDemo[2760:170260] i=1
2018-09-26 12:58:49.044 BaseRACDemo[2760:170260] i=1
2018-09-26 12:58:49.200 BaseRACDemo[2760:170260] i=1

可以看出每次进入方法i都会被初始化为0 然后+1 变为1
接下来我们看下用static修饰后的i打印出来会怎么样

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //声明一个局部变量i
  static  int i = 0;
    //每次点击view来到这个方法时让i自增
    i ++;
    //打印结果
    NSLog(@"i=%d",i);
}

打印如下:

2018-09-26 12:59:47.290 BaseRACDemo[48806:3695349] i=1
2018-09-26 12:59:49.044 BaseRACDemo[48806:3695349] i=2
2018-09-26 12:59:49.200 BaseRACDemo[48806:3695349] i=3
2018-09-26 12:59:49.290 BaseRACDemo[48806:3695349] i=4
2018-09-26 12:59:50.044 BaseRACDemo[48806:3695349] i=5
2018-09-26 12:59:50.200 BaseRACDemo[48806:3695349] i=6

这就是关键字static修饰的局部变量的作用,让局部变量永远只初始化一次,一份内存,生命周期已经跟全局变量类似了,只是作用域不变

修饰全局变量
  • 1.只能在本文件中访问,修改全局变量的作用域,生命周期不会改

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

3.extern
他的作用就是声明外部全局变量

  • 一般开发中需要在·=多个类中使用同一个字符串常量的时候,可以用const和extren的组合进行使用。

.h

#import "ZBTableViewController.h"

extern NSString *DBDefaultName;

@interface ZBStudentVC : ZBTableViewController

@end

.m

NSString *DBDefaultName = @"student";

@interface ZBStudentVC ()<PYSearchViewControllerDelegate,PYSearchSuggestionViewDataSource,PYSearchSuggestionViewDelegate>
@property (nonatomic,strong)ZBStudentVM *viewModel;
@property (strong, nonatomic) PYSearchViewController *searchVC;
@property (strong, nonatomic) PYSearchSuggestionViewController *searchSuggestion;
@end

其他类使用

    extern NSString *DBDefaultName;
    NSLog(@"%@",DBDefaultName);

其中 ,发现.h文件中也可以省略extern NSString *DBDefaultName;这句话,效果也是一样的

相关文章

网友评论

      本文标题:iOS 开发 -《Effective Objective-C 2

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