ios - Add property observer to global variable inside class in Swift -
i have variable globalvariable declared @ global scope may change @ time.
different viewcontrollers in app need react differently, when globalvariable changes.
thus desirable add property observer in each viewcontroller execute needed code when globalvariable changes.
i cannot seem achieve override or extension. what way go here?
if goal know when global variable changed, have post notification upon change:
extension nsnotification.name { static let globalvariablechanged = nsnotification.name(bundle.main.bundleidentifier! + ".globalvariable") } var globalvariable: int = 0 { didset { notificationcenter.default.post(name: .globalvariablechanged, object: nil) } } then object can add observer notification:
class viewcontroller: uiviewcontroller { private var observer: nsobjectprotocol! override func viewdidload() { super.viewdidload() // add observer; make sure `self` references `weak` or `unowned`; obviously, if don't reference `self`, that's not necessary observer = notificationcenter.default.addobserver(forname: .globalvariablechanged, object: nil, queue: .main) { [weak self] notification in // globalvariable here } } deinit { // remember remove when object deallocated notificationcenter.default.removeobserver(observer) } } note, didset mechanism not detect changes if (a) global variable reference type, i.e. class; , (b) merely mutates object global variable references rather replacing new instance. identify scenario, need use kvo or other mechanism detect mutation.
Comments
Post a Comment