iOS学习之懒加载
懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,其实是重写getter方法.
注意:如果是懒加载的话则一定要注意先判断是否已经有了,如果没有那么再去进行实例化
使用懒加载的好处:
(1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
(2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
代码示例:
//需求:创建自定义的cell,包含头像,姓名,电话,和拨打电话按钮.
//重写cell的初始化方法
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { //添加子控件 [self.contentView addSubview:self.avaterView]; [self.contentView addSubview:self.nameLabel]; [self.contentView addSubview:self.phoneLabel]; [self.contentView addSubview:self.callBtn]; } return self; } #pragma mark - 懒加载,重写getter方法 //布局子控件
- (UIImageView *)avaterView { if (!_avaterView) { self.avaterView = [[[UIImageView alloc] initWithFrame:CGRectMake(20, 5, 40, 40)] autorelease]; self.avaterView.layer.cornerRadius = 5; //设置圆角 self.avaterView.layer.masksToBounds = YES; //将超出部分裁剪掉.(默认不会裁掉,因此圆角效果不会出现) } return [[_avaterView retain] autorelease]; //安全处理 } - (UILabel *)nameLabel { if (!_nameLabel) { self.nameLabel = [[[UILabel alloc] initWithFrame:CGRectMake(70, 5, 80, 40)] autorelease]; self.nameLabel.textColor = [UIColor blackColor]; } return [[_nameLabel retain] autorelease]; } - (UILabel *)phoneLabel { if (!_phoneLabel) { self.phoneLabel = [[[UILabel alloc] initWithFrame:CGRectMake(170, 5, 150, 40)] autorelease]; self.phoneLabel.textColor = [UIColor grayColor]; } return [[_phoneLabel retain] autorelease]; } - (UIButton *)callBtn { if (!_callBtn) { self.callBtn = [UIButton buttonWithType:UIButtonTypeCustom]; self.callBtn.frame = CGRectMake(330, 5, 40, 40); [self.callBtn addTarget:self action:@selector(handleCall:) forControlEvents:UIControlEventTouchUpInside]; [_callBtn setImage:[UIImage imageNamed:@"action_call"] forState:UIControlStateNormal]; } return [[_callBtn retain] autorelease]; }