Question

I need to create a routine that save automatically a file content in a constant time period, ie, a backgroung loop that perform the save instructions. I thinked in use a recursive call of performSelector like below:

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    [self performSelector:@selector(saveMethod) withObject:nil afterDelay:kTimeConstant];

}

- (void)saveMethod{

     //The save logic should to be here

     [self performSelector:@selector(saveMethod) withObject:nil afterDelay:kTimeConstant];

}

It works, but when I get out of viewController, it still running, and it must to stop. are there any better way to execute it? Thank you!

Was it helpful?

Solution

This is probably a better implementation:

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    // Start timer and sets it to a property called saveTimer
    self.saveTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
                              target:self
                            selector:@selector(saveMethod:)
                            userInfo:nil
                             repeats:YES];
}

- (void)saveMethod:(NSTimer*)theTimer {
     // The save logic should to be here
     // No recursion
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // Stop timer
    [self.saveTimer invalidate];
}

This is running on the main thread so it is probably not the best implementation but it should work better than what you currently have.

OTHER TIPS

There is a function NSRunLoop cancelPreviousPerformRequestsWithTarget:selector:object: which allows you to cancel the performSelector call. Call this when you unload the view controller

ie.

 [NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(saveMethod) object:nil];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top