I have a UILabel extension and what to add and remove custom NSNotification in there.
public extension UILabel {
@IBInspectable var localizedText: String? {
get { return text }
set {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: LCLLanguageChangeNotification), object: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: LCLLanguageChangeNotification), object: nil, queue: .main) { [weak self] (notification) in
guard let strongSelf = self else {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: LCLLanguageChangeNotification), object: nil)
return
}
strongSelf.text = strongSelf.localizedText?.localized()
}
text = newValue?.localized()
}
}
}
Problem that I see in this solution is that when
self
is nil, its impossible to remove observer, so this notification will fire even when UILabel was removed from UIWindow stack.
Is there any workaround for this?