您所说的听起来非常适合信号量(请参阅标题下使用调度信号量来规范有限资源的使用)!我看到了你链接到的 SO Answer,我认为它不能解决UIView
动画的问题。这是我使用信号量的方法。
在您的视图控制器中添加一个实例变量dispatch_semaphore_t _animationSemaphore;
并在- init
方法中对其进行初始化:
- (id)init
{
if ((self = [super init])) {
_animationSemaphore = dispatch_semaphore_create(1);
}
return self;
}
(不要忘记在- dealloc
using 方法中释放信号量dispatch_release
。您可能还想通过 using 等待排队的动画完成dispatch_semaphore_wait
,但我会让您自己弄清楚。)
当你想排队一个动画时,你会做这样的事情:
- (void)animateSomething
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
dispatch_semaphore_wait(_animationSemaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.5 animations:^{
// Your fancy animation code
} completion:^(BOOL finished) {
dispatch_semaphore_signal(_animationSemaphore);
}];
});
});
}
您可以使用- animateSomething
模板来完成不同的事情,例如显示一个SSHUDView
或一个UIAlertView
.