用于长时间计算过程的 UIActivityIndicatorView
我有一个需要相当多时间才能执行的计算过程,因此 UIActivityIndicatorView 似乎很合适。我有一个按钮来启动计算。
我尝试将命令 [calcActivity startAnimating];
放在 IBAction
的计算开始处,并将 [calcActivity stopAnimating];
放在计算结束但没有任何显示。
接下来,我创建了一个新的 IBAction 来包含调用计算 IBAction 的开始和停止以及一个虚拟的 for 循环,以便为 startAnimating 提供一点开始的机会两者之间。这也行不通。
骨架代码如下所示:
- (IBAction)computeNow:(id)sender {
[calcActivity startAnimating];
for (int i=0; i<1000; ++i) { }
[self calcStats];
[calcActivity stopAnimating];
}
- (IBAction)calcStats {
// do lots of calculations here
return;
}
I have a computational process that takes quite a bit of time to perform so a UIActivityIndicatorView
seems appropriate. I have a button to initiate the computation.
I've tried putting the command [calcActivity startAnimating];
at the beginning of the computation in an IBAction
and [calcActivity stopAnimating];
at the end of the computation but nothing shows.
Next, I created a new IBAction
to contain the starting and stopping with a call to the computation IBAction
and a dummy for loop just to give the startAnimating a little chance to get started between the two. This doesn't work either.
The skeletal code looks like this:
- (IBAction)computeNow:(id)sender {
[calcActivity startAnimating];
for (int i=0; i<1000; ++i) { }
[self calcStats];
[calcActivity stopAnimating];
}
- (IBAction)calcStats {
// do lots of calculations here
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,正如我所评论的,您永远不应该在主线程中执行复杂的计算。它不仅会导致像您这样的情况,您的应用程序也可能会被商店拒绝。
现在, UIActivityIndicatorView 未更新的原因是,UI 实际上并未更新自身,例如,当您调用
[calcActivity startAnimating];
时,它会在代码运行后更新。在您的情况下,这意味着startAnimating
和stopAnimating
立即被调用,所以什么也没有发生。因此,“简单”的解决方案:使用 此技术 或者,可能更好,GCD。
Ok, as I commented, you should never performe complex calculations in your main thread. It not only leads to situations like yours, your app might also be rejected from the store.
Now, the reason for the UIActivityIndicatorView not being updated is, that the UI doesn't actually update itself e.g. when you call
[calcActivity startAnimating];
Instead, it gets updated after your code ran through. In your case, that means thatstartAnimating
andstopAnimating
are getting called at once, so nothing really happens.So, the 'easy' solution: Start a new thread, using either this techniques or, probably better, GCD.
谢谢你的鼓励,Phlibbo。我是这个游戏的新手,感谢所有的帮助。我没有理解您提供的链接上的所有信息,但它确实促使我进一步搜索示例。我找到了一个效果很好的。 IBAction“computeNow”由计算按钮触发。代码现在看起来像这样:
Thanks for the nudge, Phlibbo. I'm new to this game and appreciate all the help. I didn't comprehend all the info on the links you provided, but it did prod me to search further for examples. I found one that works well. The IBAction 'computeNow' is triggered by the calculation button. The code now looks like this: