最近做的一些小程序中用到了NSTimer,也在网上搜了好多关于NSTimer的用法,可是都连篇累牍,看着很是麻烦。其实啊,这里还是有些小技巧的。请看下面的代码:

@interface AppDelegate : UIResponder <UIApplicationDelegate, UITextFieldDelegate> {
    NSInteger _count;
    NSTimer *_aTimer;
}
@property (retain, nonatomic) UIWindow *window;
@end

   我在AppDelegate这个类里定义了一个_aTimer的成员变量,那么这个成员变量就可以在整个类里使用了。比如,我要实现以下的效果:提示信息在显示一段时间后可以自动显示其他信息(如下)

wKiom1LbspOz3NFoAABa5d60-7s656.jpg

wKioL1LbsnCRC18xAABL_AKtGQU076.jpg

   我要在面板上显示“输入错误”的信息后,自动变为原来的信息“QQ2013 乐在沟通 ”,就可以这样写了:

   
- (void)timerWork
{
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(nenolampRan) userInfo:nil repeats:YES];
    _aTimer = aTimer;
    [_aTimer fire];
}
- (void)timerWorkToPrompt
{
    NSTimer *aTimer = [NSTimer scheduledTimerWithTimeInterval:0.6 target:self selector:@selector(promptText) userInfo:nil repeats:YES];
    _aTimer = aTimer;
    [_aTimer fire];
}
- (void)showNenolamp
{
    [self.window sendSubviewToBack:[self.window viewWithTag:100]];
    [self handleTapGesture];
    [self timerWork];
}
- (void)returnLogin
{
    [_aTimer invalidate];
    [self.window bringSubviewToFront:[self.window viewWithTag:100]];
}
- (void)promptText
{
    _count++;
    if (_count == 2) {
        [(UILabel *)[[self.window viewWithTag:100] viewWithTag:103] setText:@"QQ2013 乐在沟通"];
        _count = 0;
        [_aTimer invalidate];
    }
}

   这样做的好处是,整个类就一个计时器,在使用完计时器时,即可直接停掉计时器,然后再调用,而且调理比较清晰。