【发布时间】:2014-11-15 04:37:23
【问题描述】:
我正在寻找一种方法来延迟加载我的变量,但我希望能够稍后将其设为 nil,然后在获取时重新创建它。例如,在出现内存警告的情况下,我想清除任何未使用的内容,然后在以后需要时重新创建它。
以下是我在 Objective-C 中的做法以及我目前对 swift 的解释。我不确定它是否保留了保持当前导航的变量。
Obj-C 实现
@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;
}
}
快速实现
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;
}
}
【问题讨论】:
标签: properties swift loading lazy-evaluation