如何减慢iOS上的一些操作

时间:2017-11-28 09:42:50

标签: ios objective-c lottie

我必须做一些复杂的计算,持续约30秒(解码一些键)。我添加并运行简单的动画(在lottie但我觉得无所谓),这样用户就不需要不耐烦了。由于计算和处理器的使用,我的动画停滞不前。

我尝试将[动画播放]方法放入主队列但没有帮助。我可以以任何方式保证我的动画有10%的处理器资源吗?或者减慢其他操作(以便不使用所有可用资源)?

项目示例:https://github.com/Redysz/Lottie-Pi-Issue

在我的iPhone上启动后,“时钟”动画可以在少数第一个电路中停留一段时间。

2 个答案:

答案 0 :(得分:2)

这是你的问题:

for(int i = 0; i < 1000; i++) {
    [self performSelectorInBackground:@selector(someHardComputations) withObject:nil];
    [self performSelectorInBackground:@selector(someHardComputations) withObject:nil];
}

(虽然我意识到someHardComputations只是一个示例,但我假设您的实际代码仍使用performSelectorInBackground:。)

这创建了一个不合理数量的后台线程(2000)。它不会让事情变得更快(你仍然只有一定数量的核心)。它只是大大增加了线程争用并干扰了主线程。在现代计划中使用performSelectorInBackground:没有充分的理由。

GCD(dispatch_queue)是您想要的工具。特别是,您希望将此工作放在具有QoS类UTILITY(也称为LOW优先级)的队列中,以便它不会与您的主队列竞争。

有关如何使用GCD的介绍,请参阅Concurrency Programming Guide。我不能给你一个确切的解决方案,因为具体如何实现这一点在很大程度上取决于someHardComputations的性质。

答案 1 :(得分:0)

我检查了你的演示应用并解决了你的问题,你应该在LOTAnimationView库上对此代码进行更改_animationSpeed = 0.5;或代码

更新删除您的1000次循环调用并使用计时器,它能够正常运行!

NSTimer *timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(someHardComputations) userInfo:nil repeats:YES];
[timer fire];


- (void)_commonInit {
   // _animationSpeed = 1;
   _animationSpeed = 0.7;
   _animationProgress = 0;
   _loopAnimation = NO;
   _autoReverseAnimation = NO;
   _playRangeEndFrame = nil;
   _playRangeStartFrame = nil;
   _playRangeEndProgress = 0;
   _playRangeStartProgress = 0;
}