how to run code in the UI thread calling it from the others ones
Swift 5+ example
DispatchQueue.main.async {
// UI code
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// UI code
}
The preferred way nowadays is using GCD, with the code you quoted in your question:
dispatch_async(dispatch_get_main_queue(), ^{
// Your code to run on the main queue/thread
});
If you prefer using a more Object-Oriented approach than GCD, you may also use an NSOperation
(like an NSBlockOperation
) and add it to the [NSOperationQueue mainQueue]
.
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Your code to run on the main queue/thread
}];
This does quite the same thing as dispatch_async(dispatch_get_main_queue(), …)
, has the advantage of being more Objective-C/POO oriented that the plain C GCD function, but has the drawback of needing to allocate memory for creating the NSOperation
objects, whereas you can avoid it using plain C and GCD.
I recommend using GCD, but there are other ways, like those two which allow you to call a selector (method) on a given object from the main thread:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
(method of NSObject so it can be called on any object)- Send
- (void)performSelector:(SEL)aSelector target:(id)target argument:(id)anArgument order:(NSUInteger)order modes:(NSArray *)modes
on the[NSRunLoop mainRunLoop]
But those solutions are not as flexible as the GCD or NSOperation
ones, because they only let you call existing methods (so your object has to have a method that already exists and does what you want to perform), whereas GCD or -[NSOperationQueue addOperationWithBlock:]
allows you to pass arbitrary code (using the block).