我正在制作一个带有计时器的应用程序。我从给定时间开始计算分钟和秒,直到 0。发生这种情况时,我会启动一个警报视图。
我的结构是这样的:
主线程方法分配一个新线程并初始化它。
线程的入口点(方法)有一个计时器,它调用一个方法来计算剩余时间,如果时间到了,则显示一个警报视图。
然而,这是正确的吗?因为现在我正在从主线程之外的另一个线程更新 GUI...这很糟糕,对吧?我还显示了该线程的警报视图。
我想制作另一种方法来封装用于更新和显示警报视图的所有逻辑,并在 nstimer 调用的方法中使用performSelectorInMainThread,但这是否正确?
谢谢你的时间。
假设确定剩余时间相当简单,只需在主线程上运行计时器即可。计时器附加到当前的运行循环,因此它不会在任何地方阻塞,并且其回调方法不应花费过多的时间来运行,因此可以很好地更新 UI。
- (void) initializeTimerWithEndTime: (NSDate *) endTime
{
// call this on the main thread & it'll automatically
// install the timer on the main runloop for you
self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
target: self
selector: @selector(timerTick:)
userInfo: endTime
repeats: YES];
#if __TARGET_OS_IPHONE__
// fire while tracking touches
[[NSRunLoop mainRunLoop] addTimer: self.countdownTimer
forMode: UITrackingRunLoopMode];
#else
// fire while tracking mouse events
[[NSRunLoop mainRunLoop] addTimer: self.countdownTimer
forMode: NSEventTrackingRunLoopMode];
// fire while showing application-modal panels/alerts
[[NSRunLoop mainRunLoop] addTimer: self.countdownTimer
forMode: NSModalPanelRunLoopMode];
#endif
}
- (void) cancelCountdown
{
[self.countdownTimer invalidate];
self.countdownTimer = nil;
}
- (void) timerTick: (NSTimer *) aTimer
{
NSDate * endDate = [timer userInfo];
NSDate * now = [NSDate date];
// have we passed the end date?
if ( [endDate laterDate: now] == now )
{
// show alert
[self cancelCountdown];
return;
}
// otherwise, compute units & show those
NSUInteger units = NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents * comps = [[NSCalendar currentCalendar] components: units
fromDate: [NSDate date]
toDate: endDate
options: 0];
[self.clockView setHours: comps.hour
minutes: comps.minute
seconds: comps.second];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)