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.
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.