1.常見懶加載方法
class ViewController: UIViewController { lazy var label: UILabel = { let label = UILabel(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .black label.font = UIFont.systemFont(ofSize: 16, weight: .bold) return label }() }
2.懶加載使用weak 還是 unowned?
[weak self] in 還是用 [unowned self] in
如果你能保證在使用過程中引用對象不會為nil,用unowned 。如果不能,那么就用weak
3.工廠方法 + 懶加載
是
class ViewController: UIViewController { lazy var label: UILabel = self.createCustomLabel() private func createCustomLabel() -> UILabel { print("被調用") let label = UILabel(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .black label.font = UIFont.systemFont(ofSize: 16, weight: .bold) return label } }
4.如果希望在多處使用,使用靜態工廠 + 懶加載
class ViewController: UIViewController { lazy var label: UILabel = UILabel.createCustomLabel() } extension UILabel { static func createCustomLabel() -> UILabel { let label = UILabel(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .black label.font = UIFont.systemFont(ofSize: 16, weight: .bold) return label } }
