Let's say I have a class called Person , with variables like firstName and lastName . I listen to changes in these variables using Cocoa's reactive structure, but let me say that I only use the built-in KVO listening, for example, didSet{} . So suppose I have this code:
let firstName:String { didSet{ self.nameDidChange() }} let lastName: String { didSet{ self.nameDidChange() }} func nameDidChange(){ print("New name:", firstName, lastName}
Each time I change the first or last name, it automatically calls the nameDidChange function. I am wondering if there are any smart steps to prevent calling the nameDidChange function twice in a row when I change both firstName and lastName .
Let's say the value in firstName is "Anders" and lastName is "Andersson" , then I run this code:
firstName = "Borat" lastName = "Boratsson"
nameDidChange will be called here twice. First he prints "New name: Borat Andersson" , then "New name: Borat Boratsson" .
In my simple mind, I think I can create a function called something like nameIsChanging() , call it whenever any of didSet , and start the timer for 0.1 seconds, and then call nameDidChange() but both of these didSet will also call nameIsChanging , so the timer will go twice and fire both times. To solve this problem, I could save the βglobalβ Timer and invalidate it and restart the account or something like that, but the more I think about the solutions, the uglier they are. Are there "best practices" here?
source share