Reputation: 178
Inside viewDidAppear
I'm putting this following code:
dispatch_async(dispatch_get_main_queue(), ^{
[NSThread sleepForTimeInterval:5.0f];
}
});
and this is blocking the UI. I was expecting this 5 seconds sleep to run in the background. What am I missing?
Upvotes: 1
Views: 1082
Reputation: 93
It's not clear to me what you're trying to accomplish by making the thread sleep in the background. Are you going to run some code after 5 seconds? You have a couple of options.
1) Use dispatch_after
instead of dispatch_async
. The following code will run on the main thread after the specified delay. If you start to type this in Xcode it should give you an autocomplete snippet. Just do whatever you need to in the completion block, including UI stuff, since you'll be on the main thread.
- (void)viewDidAppear {
[super viewDidAppear];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"5 seconds have passed");
});
}
2) Use dispatch_async
on a non-main thread. You can use the code you've written above, but modified. If you need to do things to the UI, you'll need another nested async block that runs on the main queue.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"You're now on a background thread");
[NSThread sleepForTimeInterval:5.0f];
NSLog(@"5 seconds have passed");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Do UI stuff");
})
});
Unless you have some particular reason not to (running a heavy operation on the background thread), I'd advise option #1, because it's easier to not have to remember what thread you're on if you want to make UI modifications.
Upvotes: 0
Reputation: 50
Please use performSelector as given demo below. It executes some method after given time interval in background and don't block main UI.
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear: animated];
[self performSelector:@selector(someMethod) withObject:nil afterDelay:5];
}
- (void) someMethod{
// some code statements to run after 5 seconds
}
Upvotes: 1