如何处理过多使用懒加载的问题?

前边在做项目时,为了优化内存,经常使用懒加载,当ui组件或对象过多时,这样写就很繁琐。有时也会出现问题,如在做uiview,uibutton时用懒加载,模拟器没问题。但用真机(ipnone 6,ios 8.2)测试时,只能出现backView,上边的button无法加载。格式如下:

-(UIView *)backView{
    CGFloat deviceWidth = self.view.frame.size.width;
    CGFloat backViewX = deviceWidth - 105;
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(backViewX, 0, ViewW, 80)];
        _backView.backgroundColor = [UIColor yellowColor];
        [self.view addSubview:_backView];
        _backView.hidden = YES;
    }
    return _backView;
}

-(UIButton *)delBtn{
    if (!_delBtn) {
        _delBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _delBtn.frame = CGRectMake(0, 45, ViewW, 40);
        [_backView addSubview:_delBtn];
        _delBtn.userInteractionEnabled = NO;
    }
    return _delBtn;
}

解决方法是使用了如下方法,这与使用懒加载的效果类似

-(void)setupAddDelView{
    
    CGFloat deviceWidth = self.view.frame.size.width;
    CGFloat backViewX = deviceWidth - 105;
    if (!self.backView) {
        self.backView = [[UIView alloc]initWithFrame:CGRectMake(backViewX, 0, ViewW, 80)];
        self.backView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.backView];
        self.backView.hidden = YES;
        
        CGFloat fontSize = 15;
        
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [addBtn setTitle:@"增加成员" forState:UIControlStateNormal];
        addBtn.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        [addBtn setTintColor:[UIColor colorWithRed:0/255.0 green:164/255.0 blue:223/255.0 alpha:1]];
        addBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [addBtn addTarget:self action:@selector(clickAddContacts:) forControlEvents:UIControlEventTouchDown];
        addBtn.frame = CGRectMake(0, 0, ViewW, 40);
        self.addBtn = addBtn;
        [self.backView addSubview:self.addBtn];
    }
}

以后可以考虑多使用这种。

原文地址:https://www.cnblogs.com/Apologize/p/4362765.html