OC的懒加载
#import "DemoViewController.h"
@interface DemoViewController ()
@property (nonatomic, strong) UILabel *label;
@end
@implementation DemoViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view addSubview:self.label];
//释放label
_label = nil;
//会再次调用懒加载
NSLog(@"%@", self.label);
}
-(UILabel *)label{
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.text = @"my hello";
_label.center = self.view.center;
[_label sizeToFit];
}
return _label;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
//收到内存警告,可以释放视图
//On iOS 6.0 it will no longer clear the view by default.
//iOS 6之后不会再释放视图,视图会一直保留
}
@end
Swift3.0的懒加载
import UIKit
class ViewController: UIViewController {
private var label : UILabel? = UILabel();
override func viewDidLoad() {
super.viewDidLoad()
label?.text = "hello";
label?.sizeToFit();
print(label!);
//释放label
label = nil;
//和oc不同
//懒加载的代码只会在第一次调用的时候,执行闭包,将闭包的结果保存在label的属性中
print(label!);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Swift中不要主动清理视图或控件
//因为懒加载不会再次创建
}
}