美文网首页
iOS-懒加载

iOS-懒加载

作者: 如风家的秘密 | 来源:发表于2016-08-17 20:04 被阅读59次
    原理:懒加载是当你使用某个对象时才创建,它通过在.h文件中@property定义一个实例变量(使其实例变量拥有set和get方法),并通过复写get方法实现懒加载.当需要使用时**self.实例变量**才能实现懒加载(**_实例变量没有set和get方法是不能实现加载的**)
    

    优点:它可以使代码可读性更高,对象和对象之间的独立性更强.

    一般用法:

        [self.view addSubview:label];```
    
    懒加载:
    .h文件:
    

    //自带set和get方法
    @property (nontation,strong) UILabel *titleLabel;
    @property(nonatomic,strong,readonly)UIButton *searchButton;

    .m文件
    

    //复写titleLabel 的get方法

    • (void)viewDidLoad {
      [super viewDidLoad];

      //2 懒加载形式 (当你需要使用的时候,才需要创建)
      self.titleLabel.backgroundColor = [UIColor redColor];
      self.titleLabel.text = @"我是懒加载";
      }

    
    

    -(UILabel*)titleLabel{

    if (_titleLabel == nil) {
    
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 100, 50)];      
        [self.view addSubview:_titleLabel];
    }
    
    return _titleLabel;
    

    }

    
    

    //synthesize 取属性别名,可通过_获取实例变量
    @synthesize searchButton = _searchButton;

    -(UIButton *)searchButton{

    if (_searchButton == nil) {
         _searchButton  = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.view addSubview:_searchButton];
    }
    
    return _searchButton;
    

    }

    
    运行效果:
    
    ![懒加载显示label和button](https://img.haomeiwen.com/i2471265/0629cf37e937e1c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    相关文章

      网友评论

          本文标题:iOS-懒加载

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