Pausing an NSTimer

后端 未结 4 1559
孤城傲影
孤城傲影 2021-01-15 19:14

I have a UIView with a UITableView and a UIImageView in it. The UITableView takes up the top half of the UIView

4条回答
  •  一个人的身影
    2021-01-15 19:46

    Keep a reference to the timer you create so you can stop it when needed. The next time you need it you can just create a new timer. It sounds like the best places for you to do this are in viewDidAppear: and viewWillDisappear:. I'm not sure why you are starting the timer on a new thread. You may have a good reasons for doing so but I have never needed to do this.

    //This code assumes you have created a retained property for loadNextPhotoTimer
    
        - (void)viewDidAppear:(BOOL)animated {
            [super viewDidAppear:animated];
            [self startTimer];
        }
    
        - (void)viewWillDisappear:(BOOL)animated {
            [super viewWillDisappear:animated];
            [self stopTimer];
        }
    
        - (void)startTimer {
            NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:3.0] interval:3.0 target:self selector:@selector(loadNextPhoto) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
            self.loadNextPhotoTimer = timer;
            [timer release];
        }
    
        - (void)stopTimer {
            [self.loadNextPhotoTimer invalidate];
            self.loadNextPhotoTimer = nil;
        }
    

提交回复
热议问题