Monitoring Key Values ​​and NSTimer

I am trying to observe the int (totalSeconds) property in a class (StopWatch), where the total number of seconds increases by one each time the time is triggered (one interval) by my custom class (DynamicLabel), the UILabel subclass should receive an observValueForKeyPath message every time the totalSeconds changes but he is never called. Here is the relevant code:

#import "StopWatch.h" @interface StopWatch () @property (nonatomic, strong) NSTimer *timer; @end @implementation StopWatch @synthesize timer; @synthesize totalSeconds; - (id)init { self = [super init]; if (self) { NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(fireAction:) userInfo:nil repeats:YES]; [runLoop addTimer:timer forMode:NSRunLoopCommonModes]; [runLoop addTimer:timer forMode:UITrackingRunLoopMode]; } return self; } - (void)fireAction:(NSTimer *)aTimer { totalSeconds++; } @end #import "DynamicLabel.h" @implementation DynamicLabel @synthesize seconds; - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { seconds ++; [self setText:[NSString stringWithFormat:@"%i",seconds]]; } @end 

and in the view controller:

 - (void)viewDidLoad { [super viewDidLoad]; watch = [[StopWatch alloc] init]; [watch addObserver:dLabel1 forKeyPath:@"totalSeconds" options:NSKeyValueObservingOptionNew context:NULL]; } 

where dLabel is an instance of DynamicLabel

Does anyone know why this is happening? This definitely has something to do with NSTimer because I tried the same when I change the value of totalSeconds manually to check if KVO is working and it works fine. However, when totalSeconds increases in the timer fire method, the watchValueForKeyPath method is never called. In addition, for those who are wondering why I use KVO for this, this is due to the fact that in a real application (this is just a test application) I need to display several running stopwatch (at different times) on the screen and record the last time. I would like to do this using one beat. I would really appreciate any help I can get.

Thanks,

+4
source share
1 answer

Key-Value Observing only works with properties. Your timer does not use your accessory properties to increase the value; this is an ivar change directly that will not generate KVO events. Change it to self.totalSeconds++ and it should work.

+4
source

Source: https://habr.com/ru/post/1397345/


All Articles