iOS Label Text Change with sleep()
I found interesting things.. Following code doesn't show @"One" and it show @"Two" after 3 seconds delay.. I think that @"One" need to be shown and th开发者_JAVA技巧en 3 seconds delay and then @"Two" need to pop up.. Am I wrong?
self.statusLabel.text = @"One";
sleep(3);
self.statusLabel.text = @"Two";
Thanks..
If you're doing this on the main thread, that sleep(3)
will block it, freezing the app for 3 seconds. Event processing, including things like repainting the UI, won't happen til that's over.
To get what you're expecting, try something like this:
[self.statusLabel setText:@"One"];
[self.statusLabel performSelector:@selector(setText:)
withObject:@"Two"
afterDelay:3.0];
Does the first change, then queues up an invocation performing the second change to happen in the future. Then returns control to the OS to do any necessary redrawing.
Your notion of how things should work is incorrect.
self.statusLabel.text = @"One";
This sets the value of the statusLabel field to "One". This does not immediately draw to the screen. Instead, the label will mark itself as needing display. At the end of the current run loop cycle, all the views marked as needed display will be drawn, and then their contents flushed to the screen.
Next you do:
sleep(3);
self.statusLabel.text = @"Two";
This blocks the main thread for 3 seconds (never returning to the run loop to do the work mentioned above), then changes the value to "Two" which marks the view again as needing display.
When it is eventually drawn, and flushed to the screen, the current value is "Two".
It is hard to give more specific advice about what you should be doing, because it isn't clear if there is a real problem you are trying to solve, or just experimenting in order to learn more about the frameworks.
But you should almost never use sleep, and you certainly shouldn't be blocking the main thread with sleep for several seconds.
You're wrong...
Think of it this way: when you execute code in a block you're telling iOS what you want to do. It only actually implements your instructions after you pass control back to the OS.
Your code blocks the main thread (which is a very bad thing to do).
What you need to do is set the label to "One" then set a timer that will fire in three seconds time. The code in the timer would set the text of the label to "Two."
精彩评论