I have a UIView *loadingView that simply has a black BG and a UIActivityIndicator. I want to add this to my view, and then sleep the thread for a couple seconds:
[self.window addSubview:loadingView];
loadingView.hidden=NO;
sleep(2);
Apparently, this isn’t enough time to add the view-the thread sleeps but the view isn’t added, and only appears after the 2 seconds. So I tried something like this:
-(void)sleep
{
sleep(2);
}
[self.window addSubview:loadingView];
loadingView.hidden=NO;
[self performSelector:@selector(sleep) withObject:nil afterDelay:0.01];
This displays the view before the sleep, which is the desired result. However, under these 3 lines there are several lines of code that I don’t want executed until after the sleep, and within the 0.01 seconds, all those lines are executed.
Why on earth are you sleeping the main thread for 2 seconds? Normally that’s a horrible idea, because your app will become completely unresponsive for 2 seconds.
You have the right idea in using
performSelector:withObject:afterDelay:. But there is no way to get around the fact: if you want something to happen after that delay, then it has to go in the method called after the delay. Just move those other lines of code after thesleep().(And really, if you want something to happen after two seconds, just use
performSelector:withObject:afterDelay:with a delay of two seconds.)