In short, I would like to, in Objective-C cocoa, program something that functions the same way as the following Java pseudocode:
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);
}
}
}
In other words… I’d like to spawn a daemon thread that can be as slow as it likes, without interrupting the progress or speed of any other threads, INCLUDING, the main one.
I have tried using things like the Dispatch Queue, as well as NSThread.
When using either of these, I tried to create a simple label-changer thread that toggled the label’s text from 1 to 0, indefinitely. It appeared to me, the user, to constantly be locked either at 1, or 0, randomly chosen at startup.
When using either of these, and attempting to use [NSThread sleepForTimeInterval:1];, the thread would stop executing all together after the sleepForTimeInterval call.
Furthermore, having skimmed the docs, I picked up on the fact that the run loop is not called while [NSThread sleep... is sleeping!
If it is any help, I was invoking my threads from the - (void)viewDidLoad; method.
My question for you is:
How do I stop [NSThread sleepForTimeInterval:1]; from crashing my thread, OR:
How do I start a daemon thread that invokes a method or code block (preferably a code block!)
P.S. if it makes any difference, this is for iOS
The reason for the problems you’ve seen is most likely that UIKit isn’t thread-safe, i.e. you can only use a
UILabelfrom the main thread. The easiest way to do that is to enqueue a block on the main queue (which is associated with the main thread) using GCD: