Pitfal of Variable Lazy Initialization

Variable lazy initialization is good as it ensures that your variable will not be null. However, there is a pitfall you need to be aware of. Consider the following code that lazily initializes subtaskMenu variable.

1
2
3
4
5
6
- (SubTaskMenuViewController *)subTaskMenu {
  if (!_subTaskMenu) {
    _subTaskMenu = (SubTaskMenuViewController *)self.slidingViewController.underRightViewController;
  }
  return _subTaskMenu;
}

The subTaskMenu is a variable that refers to the view controller on the right panel (ECSlidingView is used to implement the right menu). Can you think of the case that this code will causes a harmful effect? I did not aware of such effect at the time I wrote the code, until it surfaces out.

What will happen if self.slidingViewController.underRightViewController is changed?

Yes, subTaskMenu will point to the old underRightViewController, not the new one. Thus, in this case, you need to add one more condition to check if self.slidingViewController.underRightViewController value is a new one or not as well.

1
2
3
4
5
6
- (SubTaskMenuViewController *)subTaskMenu {
  if (!_subTaskMenu || (![_subTaskMenu isEqual:self.slidingViewController.underRightViewController])) {
    _subTaskMenu = (SubTaskMenuViewController *)self.slidingViewController.underRightViewController;
  }
  return _subTaskMenu;
}

Comments