简体   繁体   中英

Updating UILabel with NSTimer stops after switching UIViewControllers

I have two view controllers, both connected via Segue and using Storyboard.

In view controller 1 I have an NSTimer counting up and updating a UILabel.

When I switch to view controller 2 and back to 1 the uilabel is no longer updated.

Here is some code:

headerfile
NSString *timerTicksForCounter;

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

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateTimerLabel];
}

- (void) startLastConUpdater
{
    lastCTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:self
                                               selector:@selector(updateTimer)
                                               userInfo:nil
                                                repeats:YES];
}

-(void) updateTimerLabel
{
    NSLog(@"timer: %@", timerTicksForCounter);
    if (timerTicksForCounter) {
        NSLog(@"timer not null");
        mainTimerLabel.text = timerTicksForCounter;
    }

}

- (void)updateTimer
{

    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:stopDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"mm:ss"];

    timerTicksForCounter = [dateFormatter stringFromDate:timerDate];
    [self updateTimerLabel];
}

What do you mean it's no longer updated ? Does this mean you lose what was displayed before switching or it doesn't update anymore. If it's not updating anymore it's because you don't start the timer in the appropriate method. You could do something like :

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self startLastConUpdater];
}

This should solve both issues I mentioned above.

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