본문 바로가기
iOS/설명

[iOS] addSubView를 할 때 weak, strong 레퍼런스

by Sky Titan 2022. 2. 19.
728x90
 

Is UIView superview property weak or strong?

The UIView header states that superview property is strong open var superview: UIView? { get } But it behaves just like a weak property, i.e. if I create view1 and view2 and then call view1.addSu...

stackoverflow.com

addSubView를 할 때 weak, strong 레퍼런스

 코드에서 특정한 UIView를 addSubView를 이용해서 subView로 추가할 때, Memory leak에 대한 걱정으로 해당 subview를 weak로 선언할지 strong으로 선언할지 고민할 때가 있다.

 

 하지만 결과적으로 특별한 차이는 없다.

 왜냐하면 UIView의 superview 프로퍼티는 get만 가능한 computed property이기 때문이다.

 다만 weak로 선언하게 되면 removeFromSuperView()를 호출 시 해당 subview프로퍼티는 모든 참조를 잃어버리기 때문에 메모리가 해제되어 nil로 변한다.

 

Strong Reference


class ViewController: UIViewController {
    
    //Strong Reference
    var customView: UIView?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        customView = UIView()
        
        if let customView = customView {
            view.addSubview(customView)
        }
    }
    
    @IBAction func removeCustomView(_ sender: Any) {
        customView?.removeFromSuperview()
        print(customView)
    }
}

 strong reference로 선언한 경우엔 removeFrontSuperView()를 호출하여도 여전히 customView는 메모리에 남아있다.

 

 

Weak Reference

class ViewController: UIViewController {
    
    //Weak Reference
    weak var customView: UIView?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        customView = UIView()
        
        if let customView = customView {
            view.addSubview(customView)
        }
    }
    
    @IBAction func removeCustomView(_ sender: Any) {
        customView?.removeFromSuperview()
        print(customView)
    }
}

 weak reference로 선언한 경우엔 모든 참조를 잃어버리므로 메모리가 해제된다.

728x90

'iOS > 설명' 카테고리의 다른 글

[iOS] Lottie  (0) 2022.04.09
[iOS] point(inside:with:)  (0) 2022.04.09
[iOS] hitTest  (0) 2022.02.16
[iOS] Stretchable Image를 이용해 이미지 늘리기 (feat. 9-patch)  (0) 2022.02.08
[iOS] CoreData - (2)  (0) 2022.02.05

댓글