我想用多个UIViewControllers来维护计时器。比如,我在ViewController1中创建一个定时器,间隔60秒。20秒后,应用程序导航到ViewController2。(因此,还有40秒来执行计时器)。停留20秒后,我回到ViewController1,此时计时器应该在40秒后执行回来,然后在60秒后执行。
那我该怎么做呢?
提前谢谢。
发布于 2015-02-10 11:36:03
如果您想在多个实例中使用一个项,请使用单例设计模式进行尝试。但是就像看起来的那样,你从来没有从你的VC1导航回来,所以所有的服从对象仍然在那里。
在How to Pause/Play NSTimer?的基础上,您可以更换一些部件,使其适合您的情况。
- (void)stopTimer
{
if( timer )
{
[timer invalidate];
[timer release]; // if not ARC
timer = nil;
}
}
- (void)startTimer
{
[self stopTimer];
int interval = 1.;
timer = [[NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(countUp)
userInfo:nil repeats:YES] retain]; // retain if not ARC
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self timerStart];
}
-(void)viewWillDisappear:(BOOL)animated
{
[self stopTimer];
[super viewWillDisappear:animated];
}
-(void)countUp
{
if(timePassed++ >= 60) // defined in header
{
timePassed=0;
[self myCustomEvent];
}
}
发布于 2015-02-10 11:30:18
虽然这可能是一种具有更好实践的解决方案,但您可以在您的NSTimer
中设置AppDelegate,并使AppDelegate
管理组件来推动或弹出您的UIViewControllers
。
https://stackoverflow.com/questions/28430137
复制相似问题