iOS小经验:初始化的方法中不该设置self.view的属性

2018-09-04  本文已影响470人  小码僧

本文属 iOS小经验系列:累积平时看起来简单,容易忽视的边边角角,各路大佬敬请回避。

有个小伙伴新写了一个NextViewController,重写了两个生命周期:

- (instancetype)init{
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        
        self.view.alpha = 0;
        self.view.backgroundColor = [UIColor clearColor];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //....根据数据源source显示列表数据
}

跳转的时候用这样的代码:

- (void)nextButtonClick:(UIButton *)sender {
  
    NextViewController *nextVC = [[NextViewController alloc]init];
    nextVC.source = [self.source copy];
    [self presentViewController:nextVC animated:YES completion:nil];
}

结果发现,在执行数据源传值 nextVC.source = [self.source copy]; 代码之前,NextViewController的 viewDidLoad 死活要先执行,即使还没执行pushViewController。

造成这个问题的原因是在init的方法中设置self.view相关属性时,会导致viewDidLoad执行,即使前面的页面还没有push过来,即使还没显示。

不能混淆和乱用生命周期方法,初始化的方法中不该设置self.view的属性。

上一篇 下一篇

猜你喜欢

热点阅读