懒加载
2016-04-20 17:51
204 查看
1.懒加载基本
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法。
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化。
2.使用懒加载的好处
不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强。
每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合。
3.代码示例
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其get方法。
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化。
2.使用懒加载的好处
不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强。
每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合。
3.代码示例
#import "ViewController.h" @interface ViewController () @property(nonatomic,strong) UILabel *firstLabel; @property(nonatomic,strong) UILabel *secondLable; @property(nonatomic,strong) UIButton *leftButton; @property(nonatomic,strong) NSMutableArray *array; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.leftButton.enabled = YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /** * 延迟加载 **/ - (UILabel*)firstLabel{ //判断是否已经有了,若没有,则进行实例化 if (!_firstLabel) { _firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 300, 30)]; _firstLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:_firstLabel]; } return _firstLabel; } - (UILabel*)secondLable{ //判断是否已经有了,若没有,则进行实例化 if (!_secondLable) { _secondLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 300, 30)]; _secondLable.textAlignment = NSTextAlignmentCenter; [self.view addSubview:_secondLable]; } return _secondLable; } - (UIButton*)leftButton{ //判断是否已经有了,若没有,则进行实例化 if (!_leftButton) { _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 120, [UIScreen mainScreen].bounds.size.width, 30)]; [_leftButton setTitle:@"点击" forState:UIControlStateNormal]; [_leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [_leftButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_leftButton]; } return _leftButton; } - (NSMutableArray*)array{ //判断是否已经有了,若没有,则进行实例化 if (!_array) { _array = [[NSMutableArray alloc] initWithObjects:@"ios",@"懒加载",@"代码",@"示例", nil]; } return _array; } #pragma mark -按钮事件 - (void)leftButtonClick{ self.firstLabel.text = [NSString stringWithFormat:@"%@%@",self.array[0],self.array[1]]; self.secondLable.text = [NSString stringWithFormat:@"%@%@",self.array[2],self.array[3]]; } @end
相关文章推荐
- swift 的迭代与递归
- @synthesize name = _name;
- 对kali的若干升级问题解决方法
- IE6 select穿透问题(div 定位无法遮盖select)!
- 操作系统开发系列—12.d.扩充内核 ●
- office与pdf之间的相互转换
- spring MVC配置详解
- Delphi 中 函数参数中的 const 修饰符的本质以及注意事项
- 软件需求说明书
- CodeForces 660D
- Red Hat Enterprise Linux 4
- 几个实用的例子——Cookie读写详解
- 如何把jar包发布到maven私服
- Android初试--Android中的文件操作之SDcard操作(2)
- 如何处理 Permission denied: user=root, access=WRITE, inode="/user" 这类Hadoop权限问题问题
- Android开发中,那些让你相见恨晚的方法、类或接口
- nginx request
- 如何启动/停止/重启MySQL
- MySQL学习笔记—触发程序
- c++11 正则表达式 替换匹配子串