IOS: stop a NSTimer [duplicate]

这一生的挚爱 提交于 2019-12-20 11:56:05

问题


Possible Duplicate:
NSTimer doesn't stop

I have this code:

[NSTimer scheduledTimerWithTimeInterval:110.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];

- (void) targetMethod:(NSTimer) timer{
NSLog(@"Hello World");}

in targetMethod I can stop timer with [timer invalidate], but out of this method, How can I stop targetMethod?


回答1:


You can keep your NSTimer in a variable and stop the timer using the invalidate method. Like the following:

NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:110.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];

[myTimer invalidate];



回答2:


One way to do it is to create NSTimer *timer; as a global variable so you can have a handle to the timer. Some thing likes this:

NSTimer *timer;  //global var

timer = [NSTimer scheduledTimerWithTimeInterval:110.0
                                 target:self
                               selector:@selector(targetMethod:)
                               userInfo:nil
                                repeats:YES];

To stop timer somewhere in the same class:

[timer invalidate];


来源:https://stackoverflow.com/questions/8524290/ios-stop-a-nstimer

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