如何使我需要的一个 ntimer 失效
- (void)start{
NSTimer *mtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];
}
- (void)scheduleSomeNSTimer:(NSTimer *)timer{
NSTimer *newtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(showAction:) userInfo:nil repeats:NO];
}
- (void)showAction:(NSTimer *)timer{
NSLog(@"action show!");
}
如果我想使按函数调度的 nstimer 之一无效 - (void)addSomeNSTimer:(NSTimer *)timer
应用程序将重复创建 newtimer ,所以当我需要使这些 newnstimer 之一无效时,如何才能我找到了我需要的对象,
例如:应用程序创建 4 个 nstimers 并循环运行我如何找到其中之一并使之无效
- (void)start{
NSTimer *mtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];
}
- (void)scheduleSomeNSTimer:(NSTimer *)timer{
NSTimer *newtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(showAction:) userInfo:nil repeats:NO];
}
- (void)showAction:(NSTimer *)timer{
NSLog(@"action show!");
}
if i want invalidate one of the nstimer which schedule by function - (void)addSomeNSTimer:(NSTimer *)timer
the application will create newtimer repeatly ,so when i need to invalidate one of these newnstimer ,how can i find the object i need
for example:the application create 4 nstimers and run in loop how can i find one of them and invalidate
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该在类中保留对计时器的引用并执行以下操作:
self.myTimer = [NSTimerchedTimerWithTimeInterval:1.0 target:selfselector:@selector(scheduleSomeNSTimer:) userInfo:nil Repeats:YES];
所以每当你想要使其无效时,只需执行:
[self.myTimer invalidate];
You should keep a reference to the timer in your class and do:
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];
so whenever you want to invalidate it, just do:
[self.myTimer invalidate];
您可以通过以下方式实现此目的:
根据您的反馈,请查看以下答案。
在 .h 文件中,在数组上声明:
NSMutableArray *arrTimers;
在 .m 文件中,在该数组中创建计时器的位置添加计时器。
然后您可以像下面这样使其无效:
我希望它能解决您的问题。
干杯。
You can achieve this by below:
As per your feedback, please have a look at below answer.
in .h file, declare on Array:
NSMutableArray *arrTimers;
in .m file, add timer in this array where ever you create the timer.
Then you can invalidate it like below:
I hope it will resolve your issue.
Cheers.
To_play
是 NSTimer 对象。To_play
is NSTimer object.声明一个 NSMutableArray 并在您的 ScheduleSomeNSTimer 方法中将 newtimer 对象添加到该数组中。当您使该数组中的计时器对象无效时,您还需要将其从数组中删除。
Declare a NSMutableArray and in Your scheduleSomeNSTimer method, add the newtimer object into the array. When you invalidate a timer object in this array, you also need to remove it from the array.
您可以在不保留对计时器的引用的情况下完成此操作。请改用标志。
定时器相关源码:
You can do it without keeping a reference to the timer. Use a flag instead.
Source code related to the Timer: