I am looking for a way to lazy load my variable, but I want to be able to make it nil later and then recreate it on the get. For example in the instance that there is a memory warning i want to clear anything that isn't used and then recreate it when needed again later.
Here is how I would do it in Objective-C and my current interpretation in swift. I am not sure that it preserves the variable for keeping current navigation.
Obj-C Implementation
@property (strong, nonatomic, readwrite) UINavigationController *navController;
...
- (UINavigationController *)navController {
if (!_navController) {
UIStoryboard *tempStoryboard = [UIStoryboard storyboardWithName:@"SomeStoryboard" bundle:nil];
_navController = [tempStoryboard instantiateInitialViewController];
}
return _navController;
}
...
- (void)didReceiveMemoryWarning
{
if (![self.centerView isEqual:_navController]) {
_navController = nil;
}
}
Swift Implementation
var navController :UINavigationController? {
get {
// There is no assignment to the a variable and I can't check if the current value is nil or it recalls the get method and hence re-create it if it is nil.
let tempStoryboard = UIStoryboard(name: "Image", bundle: nil);
let tempNavController: AnyObject = tempStoryboard.instantiateInitialViewController();
return tempNavController as? UINavigationController;
}
}
...
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if (!self.centerPanel.isEqual(navController)) {
self.navController = nil;
}
}