懒加载
首先在学习懒加载前我们必须知道什么是懒加载。懒加载就是将我们平时将存放网络数据的数组,控制器的view,控件的自定义,复杂的运算逻辑等等情况下使用 的一种方法,通俗的说就是当我们需要用到的时候再加载。
懒加载的优点
- 也被成为延迟加载,可以做到用到时再加载
- 加载过了就不会再次加载,节约了系统资源
- 对于实际开发中可能会遇到的一些顺序问题,懒加载也能很好的解决
- 运行内存小,节约内存
懒加载的思路
- 在类扩展中创建一个属性
- 重写这个属性对应的getter,将要实现的逻辑放到这个getter中
- 考虑到懒加载只加载一次,那么在实现逻辑之前应该判断一下这个属性是否为空,为空才执行逻辑,否则直接返回这个属性
懒加载使用方法
先声明UILabel:
@property(nonatomic , strong)UILabel* label;
懒加载实现:
-(UILabel *)label{
if (_label == nil) { //判断是否存在实例,如果不存在则创建实例
_label = [[UILabel alloc]init];//创建实例
}
return _label;
}
注意在使用_label时不能用self.label,因为会循环调用getter方法,造成死循环。
block传值
在我们使用block传值时,必须要注意的两点:
- 首先在第二个页面必须声明一个block
- 在第一个页面跳转到第二个页面时为block中的属性赋值,完成block传值。
使用
首先我们在第二个页面,SecondViewController.h中定义一个block:
//定义Block
typedef void (^PushBlock)(NSString *);
NS_ASSUME_NONNULL_BEGIN
@interface SecondViewController : UIViewController
@property(nonatomic , strong)PushBlock pushValueString;
@property(nonatomic , strong)UITextField* textField;
@property(nonatomic , strong)NSString* textString;
@property(nonatomic , strong)UIButton* button;
@end
接着在SecondViewController.m中设置文本框和按钮,同理在ViewController.m中也设置文本框与按钮:
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
_textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 250, self.view.bounds.size.width, 50)];
_textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:_textField];
_button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_button.frame = CGRectMake(20, 350, self.view.bounds.size.width-40, 50);
_button.backgroundColor = [UIColor purpleColor];
_button.titleLabel.font = [UIFont systemFontOfSize:25.0];
_button.tintColor = [UIColor whiteColor];
[_button setTitle:@"Back" forState:UIControlStateNormal];
[_button addTarget:self action:@selector(pressback:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
}
我们同是要完成按钮对应的点击事件:
- (void)pressback: (UIButton*)sender {
// 核心代码
_pushValueString (_textField.text);
[self dismissViewControllerAnimated:YES completion:nil];
}
在ViewController.m中的按钮事件:
- (void)pressnext:(UIButton*)sender {
SecondViewController* second = [[SecondViewController alloc] init];
second.pushValueString = ^(NSString* string) {
_textFieldFirst.text = string;
};
second.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:second animated:YES completion:nil];
}
@end
这样就完成了首先在第二个页面必须声明一个block,在第一个页面跳转到第二个页面时为block中的属性赋值,完成block传值的过程。