0
votes

The scenario: the user is presented with a UIAlertController that has a button, with a handler block that updates the UI to indicate the button press. The code in the handler block is wrapped in a dispatch_async to ensure that the code runs on the main thread.

The issue: A code reviewer said the dispatch_async is unnecessary, but neither of us can find a citation to back that up. The Apple documentation about the handler only says

handler A block to execute when the user selects the action. This block has no return value and takes the selected action object as its only parameter.

I can not find anything that guarantees his position -- that a UIAlertAction handler block will always run on the main thread -- is right and in the absence of such, I am inclined to keep the dispatch_async. Is there a definitive statement either way?

1
The handler block is executed in response to a user interaction; tapping the button. UI interactions always occur on the main thread. Just as you don't need to dispatch on to the main thread in an @IBAction you do not need to dispatch here either. The reviewer is correct.Paulw11
You can test it -- try running the code without the dispatch_async. If the main thread checker doesn't catch a thread error, then you are fine.aheze
@Paulw11 - I don't think the question is "is he correct" but "is it guaranteed correct"?software evolved
It is guaranteed because it is a UI interaction.Paulw11

1 Answers

1
votes

The "definitive statement" is the fact that Paulw11 already cited: all user interaction takes place on the main thread. It is crucial to iOS programming that that fact is guaranteed; the whole runtime would break down without it. It doesn't need to be documented beyond the fact that it is documented everywhere.

Thus unless you were to find some evil way to programmatically run this method off the main thread, the only way it will ever run is because the user tapped the button and so you are indeed guaranteed you are on the main thread. You should change your inclination; the extra dispatch is an unnecessary waste.

Another way of looking at it: Apple will document whenever you will run the risk of being called back off the main thread. They don't do that here, so there is no such risk.