iosxcodemultithreadingmultitaskingshared-resource

iOS - Ensure execution on main thread


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).


Solution

  • 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.)