简体   繁体   中英

Ios - How to start a timer in different view controllers

I have a view controller A that contains a start button that when clicked uses the 'show' segue to display the next view. In the other view controller BI have a timer. How can I get the timer in view controller B to start once the start button is clicked in view controller A. So far I have the start button and timer in the same view controller, however, I want to move the timer to view controller B. Any help on how to do this ?

Use below code. //FirstViewController.m

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController()
@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)startButton:(id)sender {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SecondViewController *controller = [storyBoard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    [controller startTimer];
    [self.navigationController pushViewController:controller animated:YES];
}

// SecondViewController.h

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController {

}

-(void)startTimer;

@end

// SecondViewController.m

#import "SecondViewController.h"

@interface SecondViewController ()

@property (nonatomic,retain) NSTimer *timer;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


-(void)startTimer {

    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}
-(void)stopTimer {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

- (void)timerFired:(NSTimer *)timer {
     NSLog(@"%@",timer.fireDate);
}

-(void) viewWillDisappear:(BOOL)animated {
    [self stopTimer];
}

If the button shows the next UIViewController and also should start a timer there, why not just start the timer in the viewWillAppear method of the next ViewController?

Alternatively use the prepareForSegue in the first viewController

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"show_segue_id_from_storyboard"]) {
        ViewController2 *yourNextViewController = segue.destinationViewController;
        [yourNextViewController startTimer];
    }
}

Will call the startTimer function when your segue is triggered from the button click.

        // First VC prepareForSegue
 -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
        {
             if([segue.identifier isEqualToString:@"your segue"])
             {
                SecondVC *vc = (SecondVC *)segue.destinationViewController;
                 [vc.timer startTimer:nil];
             }
        }

        //Add below line in  second Vc 's .h file.
    @property (nonatomic, strong) NSTimer *timer;
     - (void)stopTimer:(id)sender; 
    - (void)timerFired:(NSTimer *)timer; 

        // Second VC's Public Methods
        @interface SecondVC ()
        @end

        @implementation SecondVC

        - (void)startTimer:(id)sender {
            if (!self.timer) {
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                          target:self
                                                        selector:@selector(timerFired:)
                                                        userInfo:nil
                                                         repeats:YES];
            }
        }

        - (IBAction)stopTimer:(id)sender {
            if ([self.timer isValid]) {
                [self.timer invalidate];
            }
            self.timer = nil;
        }

        - (void)timerFired:(NSTimer *)timer {
            NSLog(@"Timer fired");
        }

In the other view controller BI have a timer. How can I get the timer in view controller B to start once the start button is clicked in view controller A.

Why does the timer need to be part of any view controller? Considering that multiple controllers need to access it, and it's probably part of your app's logic rather than being directly related to the user interface, it would make more sense to move the timer into your app's model. View controller A can then tell the model that the start button was clicked, and view controller B can use KVO or notifications to watch for a change in the model that's triggered when the timer fires. Neither controller needs to even know that the timer itself even exists -- it simply becomes an implementation detail of the model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM