Swift 开发之懒加载的实例详解 /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplay
Swift 开发之懒加载的实例详解
/// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: self.runLoopMode) displayLink.isPaused = true return displayLink }()
public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } }
一个VC上放了一个按钮,然后点击按钮打印刚刚定义的懒加载对象names,按理说“--------------”应该只打印一次。
/* 用到时再加载 多次使用只加载一次 */ lazy var names :[String] = { let names = ["why", "lmj", "swd"] print("------") 按理说应该只打印一次 return names }() //方式一:仅仅创建button lazy var btn1:UIButton = UIButton() //方式二:可以设置更多btn的属性 lazy var btn :UIButton = { let btn = UIButton() btn.setTitle("按钮", for: .normal) btn.setImage(UIImage(named:""), for: .normal) return btn }()
点击按钮打印
//MARK: 点击事件 func buttonClick(_ sender:UIButton) { print("----\(names.count)") }
看看控制台的打印结果:
------ ----3 ----3 ----3 ----3
从以上结果可以看出“--------------”确实只打印了一次。
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!