Search code examples
multithreadingthread-safetyhandleruialertcontroller

iOS - In which queue selectors run on by default?


Suppose, I am presenting an UIAlertController, say myAlert, from main tread. myAlert has a action, defaultAction. I wonder if defaultActions handler by default runs on main queue or not. In other words, I wonder if there are some UI related operation inside doStuff in below code, am I required to wrap these UI tasks with main queue or it is guaranteed to run in main queue by OS?

UIAlertController* myAlert = [UIAlertController alertControllerWithTitle:@"My Alert"
                               message:@"This is an alert."
                               preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
   handler:^(UIAlertAction * action) {
      doStuff() // should I wrap doStuff in main queue, if doStuff has ui operations?
   }
];

[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];

Solution

  • You are actually asking if it runs on the main queue, not if it is thread safe.

    An object is "thread safe" if it can be accessed/modified from multiple threads without issue.

    The answer to your question is that the action closure will run on the main queue as it results from a user interaction, so you do not need to explicitly dispatch UI updates onto the main queue.