Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my iOS delegate methods always be returned on the main thread?

This is a 'best practice' question I can't seem to find a good answer for online. I am creating a static library of code, which provides several delegate methods for progress feedback amongst other things.

The library manages it's own queues, so things like downloads aren't done on the main thread obviously, but my question is should I ensure my delegate methods are always called on the main thread or is it acceptable to call them from the queued threads I am using? and rely on the developer who's using the library to check he's on the main thread if he wants to do UI updates in my delegate methods?

Cheers, Sam

like image 767
Sammio2 Avatar asked Jul 05 '13 10:07

Sammio2


People also ask

What is the difference delegates and callbacks iOS?

Callbacks are similar in function to the delegate pattern. They do the same thing: letting other objects know when something happened, and passing data around. What differentiates them from the delegate pattern, is that instead of passing a reference to yourself, you are passing a function.

How we can ensure execute code in the main thread?

If you're on a background thread and want to execute code on the main thread, you need to call async() again. This time, however, you do it on DispatchQueue. main , which is the main thread, rather than one of the global quality of service queues.

What are delegate methods in iOS?

What is delegate methods in iOS? It is an easy and influential pattern in which one object in a program works on behalf of or in coordination with, another object. The delegating object keeps a reference to the other object and at the suitable time sends a message to it.

What is main thread in iOS Swift?

The main thread is the one that starts our program, and it's also the one where all our UI work must happen. However, there is also a main queue, and although sometimes we use the terms “main thread” and “main queue” interchangeably, they aren't quite the same thing.


1 Answers

You can do it either way; you just need to document this well.

Some APIs will call you back on the main thread, some on the thread (or runloop) you used to start the work, and others don't make any guarantees at all. Some will even let you pass in a GCD queue that is used for all callbacks.

Remember the delegate/callback could block for a non-trivial amount of time, so if your API needs to resume work as soon as possible, you certainly want to dispatch to another thread or queue.

Having said all this, unless performance is critical to you or the users of your API, I would go with the most convenient for the developer which would be the main thread.

like image 163
Mike Weller Avatar answered Nov 15 '22 21:11

Mike Weller