Search code examples
iosobjective-cnsthreadperformselector

How is the better way to create background loop routines in objective-c?


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!


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.