In Android there are several ways to run some code in the main thread from others ones:
1. Activity.runOnUiThread(Runnable r)
2. new Handler.post(Runnable r);
3. View.post
What are the analogues in iOS?
dispatch_async(dispatch_get_main_queue(), ^{
});
Something else?
Thanks in advance.
The preferred way nowadays is using GCD, with the code you quoted in your question:
If you prefer using a more Object-Oriented approach than GCD, you may also use an
NSOperation(like anNSBlockOperation) and add it to the[NSOperationQueue mainQueue].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 theNSOperationobjects, 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)- (void)performSelector:(SEL)aSelector target:(id)target argument:(id)anArgument order:(NSUInteger)order modes:(NSArray *)modeson the[NSRunLoop mainRunLoop]But those solutions are not as flexible as the GCD or
NSOperationones, 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).