在 Objective c 中整个游戏的计时器计数

Timer count throughout the game in Objective c

我正在创建一个游戏应用程序,我需要在 objective c 的整个应用程序屏幕中设置 2 分钟的计时器。

我在 viewDidLoad 中创建它,但每次加载视图时它都会创建一个新实例。

这是我正在使用的代码:

@interface SomeViewController ()
{
    int timerCounter;
     NSTimer *timer;   
}
@property (strong, nonatomic) IBOutlet UILabel *timerLbl;

@end

@implementation SomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startCountdown];
}


- (void)startCountdown
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1
                                             target:self
                                           selector:@selector(countdownTimer:)
                                           userInfo:nil
                                            repeats:YES];
}

- (void)countdownTimer:(NSTimer *)timer
{
    timerCounter--;

    int minutes = timerCounter / 60;
    int seconds = timerCounter % 60;

    NSString *string = [NSString stringWithFormat:@"%02d", minutes];
    NSString *string2 = [NSString stringWithFormat:@"%02d", seconds];

    NSString *timeTotal = [string stringByAppendingString:@":"];
    NSString *timeTotal2 = [timeTotal stringByAppendingString:string2];

    _timerLbl.text = timeTotal2;
    if (timerCounter <= 0) {
        [timer invalidate];   
    }
}

每当 VC 释放

时,您需要使它无效
- (void)dealloc {
    [timer invalidate];
}

//

第二个VC可能看起来像这样

#import "ggViewController.h"
NSInteger timerCounter = 120;     // declared global to hold the value 
@interface ggViewController ()
{
    NSTimer*timer;
}
@end

@implementation ggViewController

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

   // instead of using selector use this inline callback
  timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:true block:^(NSTimer * timer) {

     timerCounter--;

     int minutes = timerCounter / 60;
     int seconds = timerCounter % 60;

     NSString *string = [NSString stringWithFormat:@"%02d", minutes];
     NSString *string2 = [NSString stringWithFormat:@"%02d", seconds];

     NSString *timeTotal = [string stringByAppendingString:@":"];
     NSString *timeTotal2 = [timeTotal stringByAppendingString:string2];

     _timerLbl.text = timeTotal2;
      if (timerCounter <= 0) {
          [timer invalidate];   
         }
    }];

}

-(void)viewDidDisappear:(BOOL)animated{

    [super viewDidDisappear:animated];

    [timer invalidate];
}


- (IBAction)gg:(id)sender {

    [self dismissViewControllerAnimated:true completion:nil];
}
@end