how to invalidate one nstimer i need
- (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
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];
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.
NSTimer *mtimer = [[NSTimer alloc] init];
mtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];
[arrTimers addObject:mtimer];
Then you can invalidate it like below:
NSTimer *myTimer = (NSTimer *)[arrTimers objectAtIndex:1];
if(myTimer != nil)
{
[myTimer invalidate];
myTimer = nil;
}
I hope it will resolve your issue.
if(timer == mtimer)
{
if(mtimer != nil)
{
[mtimer invalidate];
mtimer = nil;
}
}
if(timer == newtimer)
{
if(newtimer != nil)
{
[newtimer invalidate];
newtimer = nil;
}
}
Cheers.
To_play
is NSTimer object.
[To_play invalidate];
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.
@property(nonatomic, assign) BOOL invalidateTimer;
Source code related to the Timer:
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];
- (void)scheduleSomeNSTimer:(NSTimer *)timer
{
if(YES == invalidateTimer)
{
if([timer isValid])
{
[timer invalidate];
timer = nil;
}
}
}
精彩评论