How to stop NStimer event? [duplicate]

吃可爱长大的小学妹 提交于 2019-11-27 11:27:08

问题


Possible Duplicate:
NSTimer doesn't stop

In my application I am using NStimer to call an animation function every 3 seconds. I want to stop this timer and called another event while the timer is still running. Is this possible?


回答1:


@interface
    NSTimer *autoTimer;

@implementation

// Start timer
    autoTimer = [NSTimer scheduledTimerWithTimeInterval:(3.0)
        target:self 
        selector:@selector(autoTimerFired:) 
        userInfo:nil 
        repeats:YES];

// Stop timer:
    [autoTimer invalidate];
    autoTimer = nil;



回答2:


First, you want to keep a pointer to the timer

self.packetTimer = [NSTimer timerWithTimeInterval:CONNECTION_TIMEOUT target:self selector:@selector(connectionTimeout:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:packetTimer forMode:NSDefaultRunLoopMode];

If somewhere else in your code you want to cancel it, just call:

[self.packetTimer invalidate];
self.packetTimer = nil;


来源:https://stackoverflow.com/questions/1429571/how-to-stop-nstimer-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!