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
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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With