Reputation: 36287
I wrote a custom TableViewCell class that either returns the accessibilityLabel
that was set on it, or just return its class name as the accessibilityLabel
. Though one of the two implementations below doesn't work as expected. I'm trying to understand why...
returns correct className
class BaseTableViewCell: UITableViewCell {
var _acsLabel: String?
override var accessibilityLabel: String?{
get{
return _acsLabel ?? "\(type(of: self))"
}set (newValue) {
_acsLabel = newValue ?? ""
}
}
}
returns incorrect class name
class BaseTableViewCell: UITableViewCell {
var _acsLabel: String? = "\(type(of: self))"
override var accessibilityLabel: String?{
get{
return _acsLabel
}set (newValue) {
_acsLabel = newValue ?? ""
}
}
}
Both versions correctly return the value if I set the accessibilityLabel
, however if the value is not set the default values they return are different.
For example I subclass UserNameTableViewCell
off my BaseTableViewCell
class and don't set the accessibilityLabel
myself then:
accessibilityLabel
as UserNameTableViewCell. accessibilityLabel
as returns "(BaseTableViewCell) -> () -> BaseTableViewCell"Why is that?!
Upvotes: 0
Views: 99
Reputation: 2198
self
is not initialized by the time you call it in the second version of the code, that is why it shows the name of the super class.
If you set that variable as lazy
, it will not be set from the beginning, but will be set right when you do myInstance.accesibilityLabel,
thus making sure the name of the class is already available because self
would have been initialised.
Upvotes: 1