Initialization of property with closure

I studied ARC and strong reference loops and came across this code:

class TestClass: UIView {
  let button: UIButton = {
    let view = UIButton()
    view.frame = CGRect(x: 50, y: 50, width: 200, height: 200)
    view.backgroundColor = .blue
    view.translatesAutoresizingMaskIntoConstraints = false
    view.setTitle("Button", for: .normal)
    view.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
    return view
  }()

  @objc private func buttonClicked() {
    print("Clicked")
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    print("Object of TestClass initialized")
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  deinit {
    print("Object of TestClass deinitialized")
  }
}

The reference selfto the addTargetmethod inside the shutter does not seem to create a strong reference loop.

Can someone explain why?

Also, I noticed that if I remove inheritance from UIViewthe compiler starts to complain Use of unresolved identifier 'self'.

Can someone explain this also, why is this happening in this case and not in the first?

+4
source share
1 answer

This is not a conservation cycle, because self- this is not what you think:

, self :

(TestClass) -> () -> TestClass

, , static -like, , . .

addTarget Any? , , , NSObject.

- . , , - : , - :

enter image description here

+1

Source: https://habr.com/ru/post/1694618/


All Articles