即使使用 nsthread 接口也会冻结
我必须使用 NSThread 执行计时器,因为我需要从网络下载文本数据,否则,在 3G 连接中,它会在下载时冻结 UI。所以我使用了 NSThread 但它仍然冻结了一段时间,我不知道如何解决这个问题......
这是我用来执行计时器的代码:
- (void)viewDidLoad{
[NSThread detachNewThreadSelector:@selector(onTimerK2) toTarget:self withObject:nil];
}
- (void)onTimerK2{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(onTimerKY2) userInfo:nil repeats:YES];
[pool release];
}
- (void)onTimerKY2{
NSLog(@"working");
}
I have to perform a timer using a NSThread as I need to download text data from the web, and without that, in 3G connection it freezes the UI while downloading. So I've used a NSThread but it still freezes for a while and I don't know how to solve this....
Here's the code I'm using to perform the timer:
- (void)viewDidLoad{
[NSThread detachNewThreadSelector:@selector(onTimerK2) toTarget:self withObject:nil];
}
- (void)onTimerK2{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(onTimerKY2) userInfo:nil repeats:YES];
[pool release];
}
- (void)onTimerKY2{
NSLog(@"working");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将分离一个新线程来调用
onTimerK2
,然后该线程立即在主线程上回调一个方法,这当然会冻结您的界面。编辑
您应该在主线程之外执行任何长时间运行的工作(无论是您自己,还是使用其他地方提到的
NSURLConnection
的异步特性),然后更新您的UI 通过在该活动进行时调用主线程上的选择器。话虽如此,通过对代码进行以下更改/重新排序,您可能会取得更大的成功:
You're detaching a new thread to call
onTimerK2
, which then immediately calls a method back on the main thread, which will of course freeze your interface.Edit
You should be doing any long-running work not on the main thread (either yourself, or by using the asynchronous nature of
NSURLConnection
as mentioned elsewhere),and then updating your UI by calling selectors on the main thread as this activity progresses.Having said that, you may have more success with the following changes/reordering of your code:
目前还不清楚您如何尝试使用计时器来解决 UI 冻结问题。但是,如果您的 UI 由于下载而冻结,那么您可以尝试 异步加载,而不是使用计时器或分离另一个线程。
编辑:除非您为辅助线程配置运行循环,否则计时器将无法从该线程工作。检查运行循环管理线程编程指南。这可能比使用异步连接困难得多。
It's not very clear how you are trying to solve the UI freeze problem by using timer. But if your UI is freezing due to downloading then you can try asynchronous loading instead of using timer or detaching another thread.
EDIT: Unless you configure a run loop for secondary thread, timer is not going to work from that thread. Check the run loop management in threading programming guide. This can be a far difficult work than to use asynchronous connection.