-1

我的倒数计时器不起作用。它从屏幕上的“99”开始,然后就停在那里。它根本不动。

在我的头文件中。

@interface FirstTabController : UIViewController {
    NSTimer *myTimer; 
}

@property (nonatomic, retain) NSTimer *myTimer;

在我的 .m 文件中

- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context {
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
}

- (void)countDown {
    int counterInt = 100;

    int newTime = counterInt - 1;
    lblCountdown.text = [NSString stringWithFormat:@"%d", newTime];
}

我在我的dealloc中使'myTimer'无效。所以,谁能告诉我我的代码有什么问题。

4

1 回答 1

2

每次调用计时器方法时,您都将counterInt(返回)设置为 100。

你可以把它变成一个静态变量

变成int counterInt = 100;_static int counterInt = 100;

当然,您必须将递减的值保存在 counterInt 中。

- (void)countDown {
    static int counterInt = 100;
    counterInt = counterInt - 1;
    lblCountdown.text = [NSString stringWithFormat:@"%d", counterInt];
}

如果您需要此方法之外的变量,则应将 counterInt 设为类的实例变量。

@interface FirstTabController : UIViewController {
    int counterInt;
}

等等。

于 2011-04-04T10:26:07.593 回答