gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:32:13 26 4
gpt4 key购买 nike

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

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

这是我正在使用的代码:

@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

关于ios - Objective c 中整个游戏的计时器计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52411571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com