懒加载核心:在get方法里面进行加载,当用到时再加载而且只加载一次;
懒加载的好处:
1、就算该数据被销毁,只要程序有需要用到时,还是可以加载出来
2、使用懒加载代码可读性更高
3、对象和对象之间的独立性更强
注意:执行懒加载之前一定要先判断是否已经有了,如果没有再去进行实例化
<span style="font-size:14px;">#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UILabel *titleLable;
@property(nonatomic,strong)UIButton *loginButton;
@property(nonatomic,strong)UIImageView *myImageV;
@property(nonatomic,strong)NSArray *array;
@property(nonatomic,assign)NSUInteger index;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setAttributes];
}
// 对属性的具体设置
-(void)setAttributes{
// 初始化下标值为1
self.index = 0;
// 设置图片
[self.myImageV setImage:[UIImage imageNamed:@"1"]];
// 设置label的标题和标题颜色
self.titleLable.text = @"我是标题label";
self.titleLable.textColor = [UIColor cyanColor];
// 设置切换按钮的标题和背景颜色
[self.loginButton setTitle:@"切换图片" forState:UIControlStateNormal];
self.loginButton.backgroundColor = [UIColor orangeColor];
// 切换按钮的响应事件
[self.loginButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
// 设置数组的图片数据
self.array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7"];
}
//@synthesize的作用是_myImageV相当于myImageV
@synthesize myImageV = _myImageV;
@synthesize array = _array;
// UILabel的懒加载,只调用一次
-(UILabel *)titleLable{
// 先判断再执行
if (_titleLable == nil) {
_titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 40)];
[self.view addSubview:_titleLable];
}
return _titleLable;
}
// UIButton的懒加载,只调用一次
-(UIButton *)loginButton{
// 先判断再执行
if (_loginButton == nil) {
_loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
_loginButton.frame = CGRectMake(0, 0, 200, 30);
_loginButton.center = CGPointMake(self.view.bounds.size.width*0.5, self.view.bounds.size.height*0.5);
[self.view addSubview:_loginButton];
}
return _loginButton;
}
// UIImageView的懒加载,只调用一次
-(UIImageView *)myImageV{
// 先判断
if (_myImageV == nil) {
_myImageV = [[UIImageView alloc] initWithFrame:CGRectMake(60, 50, 300, 300)];
[self.view addSubview:_myImageV];
}
return _myImageV;
}
//NSArray的懒加载,只加载一次
-(NSArray *)array{
// 先判断
if (_array == nil) {
_array = [NSArray array];
}
return _array;
}
#pragma mark - 切换按钮的响应事件
-(void)buttonAction:(UIButton *)button {
self.index++;
// 如果切换到最后一张图片,返回第一张
if (self.index > 6) {
self.index = 0;
}
// 重新设置self.myImageV,实现图片切换
[self.myImageV setImage:[UIImage imageNamed:self.array[self.index]]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
</span>