首页 > 学院 > 开发设计 > 正文

Swift3.0 -- 懒加载和OC的区别

2019-11-09 15:15:48
字体:
来源:转载
供稿:网友

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 UIKitclass 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中不要主动清理视图或控件        //因为懒加载不会再次创建    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表