我想观察一个类(秒表)中的一个int属性(秒),其中总秒数每增加一次时间激发(一秒间隔)我的自定义类(DynamicLabel )每次totalSeconds发生变化时,UILabel的子类应该会收到一个observeValueForKeyPath消息,但它永远不会被调用。下面是相关代码:键值观察和NSTimer
#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是否正常工作,并且工作正常。但是,当totalSeconds在计时器的fire方法中增加时,observeValueForKeyPath方法永远不会被调用。此外,对于那些想知道为什么我为此使用KVO的人,这是因为在真实应用程序中(这只是一个测试应用程序),我需要在屏幕上显示多个正在运行的秒表(并在不同的时间)并记录所用时间倍。我想用一个时钟做这个。我非常感谢我能得到的任何帮助。
谢谢,
非常感谢!多么愚蠢的疏忽。 – 2012-02-20 01:26:18
比大脑瘫痪,深种子虫或逻辑错误更好的监督。 :) – LucasTizma 2012-02-20 01:29:02