Iphone 键值观察和NSTimer

Iphone 键值观察和NSTimer,iphone,objective-c,ios,nstimer,key-value-observing,Iphone,Objective C,Ios,Nstimer,Key Value Observing,我试图观察一个类(秒表)中的int属性(totalSeconds),其中每当触发时间(1秒间隔)时,totalSeconds都会增加1。我的自定义类(DynamicLabel)每次totalSeconds更改时,UILabel的子类都会收到observeValueForKeyPath消息,但从未调用它。以下是相关代码: #import "StopWatch.h" @interface StopWatch () @property (nonatomic, strong) NSTimer *tim

我试图观察一个类(秒表)中的int属性(totalSeconds),其中每当触发时间(1秒间隔)时,totalSeconds都会增加1。我的自定义类(DynamicLabel)每次totalSeconds更改时,UILabel的子类都会收到observeValueForKeyPath消息,但从未调用它。以下是相关代码:

#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
在视图控制器中:

- (void)viewDidLoad
{
    [super viewDidLoad];
    watch = [[StopWatch alloc] init];
    [watch addObserver:dLabel1 forKeyPath:@"totalSeconds" options:NSKeyValueObservingOptionNew context:NULL];
}
其中dLabel是DynamicLabel的一个实例

有人知道为什么会这样吗?它肯定与NSTimer有关,因为我也尝试过同样的方法,手动更改totalSeconds的值,以检查KVO是否正常工作,并且工作正常。但是,当计时器的fire方法中的totalSeconds增加时,将永远不会调用observeValueForKeyPath方法。另外,对于那些想知道我为什么要使用KVO的人来说,这是因为在真正的应用程序(这只是一个测试应用程序)中,我需要在屏幕上显示多个正在运行的秒表(在不同的时间),并记录经过的时间。我想用一个时钟来做这个。我真的很感激能得到的任何帮助


谢谢,

键值观察仅适用于属性。计时器没有使用属性访问器来增加值;它直接更改ivar,不会生成任何KVO事件。将其更改为
self.totalSeconds++
,它应该会工作。

与其说是一个破坏大脑、根深蒂固的错误或逻辑错误,不如说是一个愚蠢的疏忽。:)