samouray samouray - 5 months ago 22
iOS Question

IOS - Objective C - How to stop executing periodic function when exiting the view?

I have a function in one of my viewControllers that I execute once every 10 seconds.

I want this function to stop it's execution when I exit the view.

I tried this peace of code :

-(void)viewWillDisappear:(BOOL)animated
{
NSError *error2;
if ([_managedObjectContext save:&error2] == NO) {
NSAssert(NO, @"Save should not fail\n%@", [error2 localizedDescription]);
abort();
}
else
NSLog(@"Context Saved");



[self stopTimer];
NSLog(@"View will disappear now");
}


It is basicly calling the method stopTimer that will give a value of null to the timer.

- (void) stopTimer
{
[timer invalidate];
timer = nil;
}


My problem is that my function keeps on executing even if I get out of my view. and never stops. How can I fix this?

EDIT:

This is the function called by my nstimer:

- (void) MyFunctionCalledByNSTimer
{
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
target:self selector:@selector(Function1) userInfo:nil repeats:YES];

}


I declare my nstimer in .m of my viewController

NSTimer *timer;


If you need more peaces of code just ask and I will edit the question.

Answer

May be issue happening because of creating more than one timer and invalidating only what you have reference to.

So, may be modifying MyFunctionCalledByNSTimer like below will solve your problem:

- (void) MyFunctionCalledByNSTimer
{
     if(!timer){

          timer  =  [NSTimer scheduledTimerWithTimeInterval:10.0f
                                     target:self selector:@selector(Function1) userInfo:nil repeats:YES];
     }

}

Now, only one timer reference will be there and [timer invalidate] will invalidate timer.

Comments