我有一个简单的应用程序,它在 appDelegate 中有一个 NSTimer 对象,所有视图都可以访问它。应用程序的结构是一个 UINavigationController。当我触发 NSTimer 对象时,我的 UILabel 正在使用正确的倒计时功能进行更新,但是当我返回 rootViewController 并返回倒计时计时器视图时,我的 UILabel 正在使用当前倒计时时间进行更新,但没有后续更新UILabel 发生。我错过了什么?我已经完成了确保 UILabel 对象不是 nil 的研究,我在 viewDidAppear 方法上调用了该函数,但似乎没有任何效果!这是代码:
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
}
@property (nonatomic, retain) NSTimer *countdownTimer;
AppDelegate.m
@implementation AppDelegate
@synthesize countdownTimer;
CountdownTimerViewController.h
#import "AppDelegate.h"
enter code here
@interface CountdownTimerViewController : UIViewController {
enter code here
AppDelegate *appdelegate;
}
@property (strong, nonatomic) IBOutlet UILabel *labelCountdownTimer;
@property (strong, nonatomic) IBOutlet UIButton *buttonStartTimer;
@property (strong, nonatomic) IBOutlet UIButton *buttonStopTimer;
- (IBAction)startTimer:(id)sender;
- (IBAction)stopTimer:(id)sender;
CountdownTimerViewController.m
@implementation CountdownTimerViewController
@synthesize labelCountdownTimer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Instatiating Appdelegate
if(!appdelegate)
appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (void) viewDidAppear:(BOOL)animated {
if ([appdelegate.countdownTimer isValid]) {
[self countDown];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Button Action Methods
- (IBAction)startTimer:(id)sender {
[self updateCounter];
}
- (IBAction)stopTimer:(id)sender {
[appdelegate.countdownTimer invalidate];
labelCountdownTimer.text = @"00:00:00";
}
int countLimit=30; //seconds
NSDate *startDate;
- (void)countDown {
if([[NSDate date] timeIntervalSinceDate:startDate] >= countLimit) {
[appdelegate.countdownTimer invalidate];
return;
}
else {
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = -([currentDate timeIntervalSinceDate:startDate]);
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString = [dateFormatter stringFromDate:timerDate];
NSLog(@"timeString: %@",timeString);
NSLog(@"labelCountdownTimer: %@",labelCountdownTimer);
labelCountdownTimer.text = timeString;
}
}
- (void)updateCounter {
labelCountdownTimer.text = @"00:00:00";
startDate = [NSDate date];
appdelegate.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(countDown)
userInfo:nil
repeats:YES];
}