iOS - Ensure execution on main thread

IosXcodeMultithreadingMultitaskingShared Resource

Ios Problem Overview


I want to know how to call my function on the main thread.

How do I make sure my function is called on the main thread?

(this follows a previous question of mine).

Ios Solutions


Solution 1 - Ios

This will do it:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

Solution 2 - Ios

When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

Solution 3 - Ios

> there any rule I can follow to be sure that my app executes my own code just in the main thread?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

If you want to be really sure, you can do things like

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)

Solution 4 - Ios

i think this is cool, even tho in general its good form to leave the caller of a method responsible for ensuring its called on the right thread.

if (![[NSThread currentThread] isMainThread]) {
    [self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO];
    return;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser236739View Question on Stackoverflow
Solution 1 - Iosshoughton123View Answer on Stackoverflow
Solution 2 - IosCarlJView Answer on Stackoverflow
Solution 3 - IosAmy WorrallView Answer on Stackoverflow
Solution 4 - IosSean DanzeiserView Answer on Stackoverflow