我对一个组件进行了子类化(它看起来像圆圈,里面有一张图片(NSView 子类))。
我想每 X 次更改一次图片(使其看起来像动画)。
当我在主视图 Controller 中绘制 1 个子类时,一切都正常,但是当我添加更多子类时,每个子类的图片变化速度都会更快。
(我使用 NSTimer
触发图片更改)
我假设发生此问题是因为同一队列上有多个 NSTimers
但是我尝试使用
NSTimer *uiTimer = [NSTimer timerWithTimeInterval:(1.0 / 5.0) target:self selector:@selector(changePicture) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:uiTimer forMode:NSRunLoopCommonModes];
它没有解决问题(我认为是因为它仍在主线程上)
所以我想出了 NSThread
解决方案
[NSThread detachNewThreadSelector:@selector(updateModel) toTarget:self withObject:nil];
- (void) updateModel
{
[NSTimer scheduledTimerWithTimeInterval:secondsBetweenUpdates
target:self
selector:@selector(changePicture)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] run];
}
它的行为有点不同(但仍然没有运气,因为我有更多的子类,图片变化更快)。
我的最后一次拍摄是这个解决方案:
// Update the UI 5 times per second on the main queue
// Keep a strong reference to _timer in ARC
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, (1.0 / 5.0) * NSEC_PER_SEC, 0.25 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
[self changePicture];
});
// Start the timer
dispatch_resume(_timer);
我通常不会放弃,但我已经尝试解决它 3 天了......而且我认为我需要如何做到这一点的建议,以便它能够按预期工作。
最佳答案
如果您使用 GCD,我建议您使用 dispatch_after
,例如:
float delayTime = 0.2f;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(delayTime * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[self changePicture];
});
关于objective-c - 多个 NSTimers 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23908574/