How to references a subview in an UIView subclasses

How would you recommend to reference a subview in an UIView subclass?


class MyTableViewCell: UITableViewCell {

    weak private(set) var titleLabel: UILabel?
    weak private(set) var addressSwitch: UISwitch?

    override init(frame: CGRect) {
        let titleLabel = UILabel()
        let addressSwitch = UISwitch()

        self.titleLabel = titleLabel   
        self.addressSwitch = addressSwitch

        super.init(frame: frame)
      
        addSubview(titleLabel)
        addSubview(addressSwitch)
    }
}


class MyTableViewCell: UITableViewCell {

    let titleLabel: UILabel = UILabel()
    let addressSwitch: UISwitch = UISwitch()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(titleLabel)
        addSubview(addressSwitch)
    }
}


These are the two options:


1. with a weak reference

2. with a strong reference


What would you recommend? If you have a link to apple documentation which includes a recommendation please let me know.

Answered by Frameworks Engineer in 43341022

junkpile is pointing out that you may need temporarily remove a subview from the view hierarchy - in which case you need to hold a strong reference to the view yourself in order to prevent it from being immediately deallocated.


Apple's sample code uses weak references for IBOutlets except in the above case.

If your subview is always guaranteed to be in the view hierarchy, as it is in your code snippets, then whether your property is strong or weak won't make any difference. A strong reference will always be held by the superview so the subview will never be deallocated by itself.


But if at some point you called self.titleLabel.removeFromSuperview(), if you only had a weak reference in your property, the object would be deallocated at that point.

Your last argument is why I prefere to use a weak references. An UIView subclass is a representation of several views. If a view isn't include in the viewhierachy should it still be an instance variable of the subclass?

Accepted Answer

junkpile is pointing out that you may need temporarily remove a subview from the view hierarchy - in which case you need to hold a strong reference to the view yourself in order to prevent it from being immediately deallocated.


Apple's sample code uses weak references for IBOutlets except in the above case.

How to references a subview in an UIView subclasses
 
 
Q