简而言之,我想在Objective-C可可中编写与以下Java伪代码相同的功能:
public class MainClass
{
public void mainmethod() //Gets called at start of program
{
UILabel label = CreateAButton();
new DaemonClass(label).start();
//Do things without being interrupted by the Daemon class sleeping or lagging
}
}
public class DaemonClass extends Thread
{
public UILabel label;
public DaemonClass(UILabel lbl)
{
setDaemon(true);
label = lbl;
}
public void run()
{
int i = 0;
while(true)
{
i++;
i = i%2;
UILabel.setText("" + i);
Thread.sleep(1000);
}
}
}
换句话说...我想产生一个尽可能慢的守护进程线程,而不中断其他线程(包括主线程)的进度或速度。
我试过使用
Dispatch Queue
和NSThread
之类的东西。使用这两种方法时,我都尝试创建一个简单的标签更换器线程,该线程将标签的文本从1无限期地切换为0。在我看来,用户经常被锁定为1或0,这是在启动时随机选择的。
当使用其中任何一个并尝试使用
[NSThread sleepForTimeInterval:1];
时,该线程将在sleepForTimeInterval调用之后停止一起执行所有操作。此外,浏览了文档后,我发现
[NSThread sleep...
处于休眠状态时不会调用run循环!如果有帮助,我正在从
- (void)viewDidLoad;
方法调用线程。我对您的问题是:
如何阻止
[NSThread sleepForTimeInterval:1];
崩溃,或者:如何启动守护程序线程,该线程调用方法或代码块(最好是代码块!)
附言如果有什么不同,这是针对iOS
最佳答案
您看到的问题的原因很可能是UIKit不是线程安全的,即您只能在主线程中使用UILabel
。最简单的方法是使用GCD在主队列(与主线程相关联)上排队一个块:
dispatch_async(dispatch_get_main_queue(), ^{
myLabel.text = @"whatever";
});