簡體   English   中英

鍵值觀察和NSTimer

[英]Key-Value-Observing and NSTimer

我正在嘗試觀察類(StopWatch)中的int屬性(totalSeconds),其中每次觸發時間(一秒間隔)時總秒數加1我的自定義類(DynamicLabel)UILabel的子類應該接收observeValueForKeyPath消息每次totalSeconds改變但從未調用。 這是相關代碼:

#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在timer的fire方法中遞增時,observeValueForKeyPath方法永遠不會被調用。 此外,對於那些想知道我為什么使用KVO的人來說,這是因為在真實應用程序中(這只是一個測試應用程序),我需要在屏幕上顯示多個運行秒表(在不同時間)並記錄已過去倍。 我想用一個時鍾做這個。 我真的很感激我能得到的任何幫助。

謝謝,

鍵值觀察僅適用於屬性。 您的計時器沒有使用您的屬性訪問器來增加值; 它正在直接改變ivar,不會產生任何KVO事件。 將其更改為self.totalSeconds++ ,它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM