Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all articles
Browse latest Browse all 16750

Swift - Timer not able to access updated instance property

$
0
0

Im my react native project's native module I need to send some data periodically from Objective-C to Swift so I am using NSNotificationCenter. I receive the data successfully in my Swift class, inside the function attached to the observer, and I store it in a property.

If I access this property from any instance method call I can see that the value has updated.

However if I access the same property in the selector function attached to the Timer it appears as if the value has not been updated and I cannot figure out why? It seems as if the timer selector function does not have access to anything except the initial value of the property - I have also tried passing the property as part of userInfo to the Timer but the issue is the same.

[[NSNotificationCenter defaultCenter] postNotificationName:@"stateDidUpdate" object:nil userInfo:state];
class StateController {  var state: Dictionary<String, Any> = Dictionary()  var timer: Timer = Timer()    func subscribeToNotifications() {    NotificationCenter.default.addObserver(        self, selector: #selector(receivedStateUpdate),        name: NSNotification.Name.init(rawValue: "stateDidUpdate"), object: nil)    }    @objc func receivedStateUpdate(notification: NSNotification) {        if let state = notification.userInfo {            self.state = (state as? Dictionary<String, Any>)!            print("\(self.state)") // I can see that self.state has been updated here        }    }    func runTimer() {        self.timer = Timer(timeInterval: 0.1, target: self, selector: #selector(accessState(timer:)), userInfo: nil, repeats: true)        self.timer.fire()        RunLoop.current.add(self.timer, forMode: RunLoop.Mode.default)        RunLoop.current.run(until: Date(timeIntervalSinceNow: 2))    }     @objc func accessState(timer: Timer) {        print("\(self.state)") // state is an empty Dictionary when accessed here    }    func printState() {"\(self.state)" // value printed is the updated value received from the notification    }}

Viewing all articles
Browse latest Browse all 16750

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>