gpt4 book ai didi

iphone - 线程和 NSTimer

转载 作者:行者123 更新时间:2023-12-03 20:34:34 27 4
gpt4 key购买 nike

我正在制作一个带有计时器的应用程序。我从给定时间开始计算分钟和秒,直到 0。发生这种情况时,我启动一个警报 View 。

我的结构是这样的:

主线程方法分配一个新线程并初始化它。线程的入口点(方法)有一个计时器,它调用一个方法来计算剩余时间,如果时间到了,则显示一个警报 View 。

但是,这是正确的吗?因为现在我正在从主线程之外的另一个线程更新 GUI...这很糟糕,对吗?我还显示了该线程的警报 View 。

我想制作另一种方法来封装用于更新和显示警报 View 的所有逻辑,并在 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];
}

关于iphone - 线程和 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4949438/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com