Change iOS label text with sleep ()

I found interesting things. The following code does not show @ โ€œOne,โ€ and it shows @ โ€œTwoโ€ after a 3 second delay .. I think that @ โ€œOneโ€ needs to be shown, and then a delay of 3 seconds, and then โ€œTwoโ€ needs to pop up. I'm wrong?

self.statusLabel.text = @"One"; sleep(3); self.statusLabel.text = @"Two"; 

Thanks..

+4
source share
3 answers

If you do this in the main thread, sleep(3) block it, freezing the application for 3 seconds. Event handling, including things like redrawing the user interface, will not happen before that.

To get what you expect, try something like this:

 [self.statusLabel setText:@"One"]; [self.statusLabel performSelector:@selector(setText:) withObject:@"Two" afterDelay:3.0]; 

Does the first change, and then calls the sequence of the second change, which will happen in the future. Then it returns OS control to perform the necessary redrawing.

+7
source

Your idea of โ€‹โ€‹how it should work is wrong.

 self.statusLabel.text = @"One"; 

This sets the value of the statusLabel field to One. This does not immediately refer to the screen. Instead, the shortcut will mark itself as the required display. At the end of the current cycle of the cycle of the cycle, all images marked as necessary displays will be drawn, and then their contents will be cleared of the screen.

Next you will do:

 sleep(3); self.statusLabel.text = @"Two"; 

This blocks the main thread for 3 seconds (never returning to the start cycle to complete the above work), then changes the value to โ€œTwoโ€, which marks the view again as it should be displayed.

When it is ultimately drawn and reddened on the screen, the current value is Two.

It is difficult to give more specific advice on what you should do, because it is not clear if there is a real problem that you are trying to solve, or just experimenting to find out more about the infrastructure.

But you will almost never use sleep, and you certainly should not block the main flow of sleep for a few seconds.

+2
source

You're wrong...

Think of it this way: when you execute code in a block, you tell iOS what you want to do. It only actually implements your instructions after you transfer control back to the OS.

Your code blocks the main thread (which is very bad).

What you need to do is set the label to โ€œOne,โ€ and then set a timer that will fire after three seconds. The code in the timer would set the label text to Two.

+1
source

Source: https://habr.com/ru/post/1369400/


All Articles