【发布时间】:2018-09-19 17:48:48
【问题描述】:
我正在创建一个游戏应用程序,我需要在目标 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];
}
}
【问题讨论】:
标签: ios objective-c nstimer