NSTimer versus separate thread - which one to choose? - objective-c

Let's assume we have simple UI and for whatever reason, every 5 seconds a UILabel needs to be updated.
I can now either setup an NSTimer which does the job, or create a separate thread which runs endlessly, sleeps 5 seconds, does its thing, sleeps again and so on.
Which one would I choose to go for? What are the differences?

You have to do UI operations on the main thread anyway, so unless your doing some processing prior to setting the label there would be no benefit of using another thread.

The UI can only be updated on the main thread of any program. If you want to do calculations for the label in a separate thread, that's perfectly fine, but the code to update your UI will have to operate on the main thread (or, you can use performSelectorOnMainThread:withObject:waitUntilDone: to call setText: on your label and have it operate correctly).

Use NSTimer.
Why?
As soon as you introduce extra threads, you introduce the possibility of a whole new class of bugs i.e. thread synchronisation issues. These tend to be very hard to diagnose and resolve due to their indeterminate nature.
You have to do UI updates on the main thread anyway. So your thread would have to do -performSelectorOnMainThread:withObject:waitUntilDone: to update the UI.
If the calculations for the label take a while (don't just assume they do, try it the simple way first and see), have your timer kick off an NSOperation to do the calculations and then have the NSOperations call -performSelectorOnMainThread:withObject:waitUntilDone: when it has finished.

Related

Detect when block is added to Grand Central Dispatch?

I have an iOS application using NSThreads for concurrency tasks. I will try to migrate it to be using the Grand Central Dispatch (GCD) for handling concurrency.
The problem is that the app needs information regarding how many threads has been created since a given time. And how many threads that was spawned since that given time is currently running.
At the moment this is done by creating a category that does a method swizzling on the -main method in NSThread. In the new swizzled method it simply increments the total number of threads running and then decrement the same variable before the new swizzled -main method returns.
The problem is that when I use GCD dispatch_async it does not create a NSThread, hence my category approach does not work. How can I achieve the same while using GCD to handle concurrency?
What I would like to detect is when a new block is added to GCD, and when that block has been executed.
Any suggestions on how to achieve the same is very welcome.
EDIT
Many thanks to #ipmcc and #RyanR for helping me out on this. :) I believe I need to tell some more about the background and what I am trying to accomplish.
What I am actually trying is to extend the iOS testing framework Frank. Frank embeds a small web-server within a given app which enables sending HTTP request to the iOS application and thereby simulating events, a swipe or a tap gesture as an example.
I would like to extend it in a way that enables it to wait until all work triggered by a specific simulated event has ended before returning upon a request.
However I found it hard to detect exactly what work was triggered by the received event. And thats how I came to the solution to just reset a thread counter and then increment this counter for all created threads after the event was simulated, and decrement it when the threads are finishing. And then block until threads count became zero again. I know this approach is not perfect either, and it wont work with GCP.
Is there any other way to achieve it? Another possible solution which I have thought of is to specify that everything must run synchronized except the thread handling the HTTP request. However I don't know if this possible.
Any suggestions on how to achieve blocking after each simulated event until work triggered by that event has completed?
The problem is that the app needs information regarding how many
threads has been created since a given time. And how many threads that
was spawned since that given time is currently running.
You will not be able to get this information from GCD. One of the points of GCD is that you do not manage the thread pool. It is opaque. You'll note that even pthreads, the underlying threading library on which NSThread and GCD are built, does not have a (public) means to enumerate all existing threads or get the number of running threads. This is not going to be doable without hard core low level hackery. If you need to control or know the number of threads, then you need to be the one to spawn and manage them, and GCD is the wrong abstraction for you.
At the moment this is done by creating a category that does a method
swizzling on the -main method in NSThread. In the new swizzled method
it simply increments the total number of threads running and then
decrement the same variable before the new swizzled -main method
returns.
Note that this only tells you the number of threads started using NSThread. As mentioned, NSThread is a fairly high level abstraction on top of pthreads. There is nothing to prevent library code from spawning its own threads using the pthreads API that will be invisible to your count.
The problem is that when I use GCD dispatch_async it does not create a
NSThread, hence my category approach does not work. How can I achieve
the same while using GCD to handle concurrency?
In short, you can't. If you want to go forth and patch functions all over the various frameworks, then you should look up a library called mach_override. (But please don't.)
What I would like to detect is when a new block is added to GCD, and
when that block has been executed.
Since GCD uses thread pools, the act of adding a block does not imply a new thread. (And that's sorta the whole point.)
If you have some limited resource whose consumption you need to manage, the traditional way to do that would be with a limiting semaphore, but that is just one option.
This whole question just reeks of a poor design. Like the number of pthreads, GCD's queue widths are opaque/non-public. Your previous solution was not particularly viable (as discussed), and further efforts are likely to yield similarly poor solutions. You should really rethink your architecture such that knowing how many threads are running isn't important.
EDIT: Thanks for the clarification. There's not really a generic way, from the outside, to tell when all the "work" is done. What if an action sets up a timer that won't call back for ten minutes? At the extreme, consider this: the main runloop continues to spin for the entire life of the app, and as long as the main runloop is spinning, "work" could be being done on it.
In order to detect "doneness" your app has to signal doneness. In order to signal doneness, the app has to have some way (internal to itself) to know it's done. Put differently, the app can't tell something else (i.e. Frank) something it doesn't know. One way to go about this would be to encapsulate all the work you do in your app in NSOperations. NSOperation/NSOperationQueue provide good ways of reporting "doneness." At the simplest level, you could wrap the code where you kickoff work in an NSBlockOperation, then add a completion block to that operation that signals something else when it's done, and enqueue it to an NSOperationQueue for execution. (You could also do this with dispatch_group and dispatch_group_notify if you prefer working in the GCD style.)
If you have specific questions about how to package up your app's work into NSOperations, I would suggest starting a new question.
You can hook into the dispatch introspection functions (introspection.h, methods all start with dispatch_introspection), but you have to link with that library which is supposed to be only for debugging. I don't think you can include that in a release build. Your best bet would be to encapsulate GCD into your own object, so all your code submits blocks to execute through that object and it submits them to GCD after tracking whatever you're interested in. You won't be able to track thread consumption though, because GCD intentionally abstracts that and reuses threads.

Should my block based methods return on the main thread or not when creating an iOS cloud integration framework?

I am in the middle of creating a cloud integration framework for iOS. We allow you to save, query, count and remove with synchronous and asynchronous with selector/callback and block implementations. What is the correct practice? Running the completion blocks on the main thread or a background thread?
For simple cases, I just parameterize it and do all the work i can on secondary threads:
By default, callbacks will be made on any thread (where it is most efficient and direct - typically once the operation has completed). This is the default because messaging via main can be quite costly.
The client may optionally specify that the message must be made on the main thread. This way, it requires one line or argument. If safety is more important than efficiency, then you may want to invert the default value.
You could also attempt to batch and coalesce some messages, or simply use a timer on the main run loop to vend.
Consider both joined and detached models for some of your work.
If you can reduce the task to a result (remove the capability for incremental updates, if not needed), then you can simply run the task, do the work, and provide the result (or error) when complete.
Apple's NSURLConnection class calls back to its delegate methods on the thread from which it was initiated, while doing its work on a background thread. That seems like a sensible procedure. It's likely that a user of your framework will not enjoy having to worry about thread safety when writing a simple callback block, as they would if you created a new thread to run it on.
The two sides of the coin: If the callback touches the GUI, it has to be run on the main thread. On the other hand, if it doesn't, and is going to do a lot of work, running it on the main thread will block the GUI, causing frustration for the end user.
It's probably best to put the callback on a known, documented thread, and let the app programmer make the determination of the effect on the GUI.

When do I need to worry about thread-safety in an iOS application?

When writing the usual view controller code, can I assume that this will only be called from a single event-loop thread? What kind of classes do I need to make thread-safe? What are the usual situations where multiple threads are involved?
The concurrency programming guide is good. Here are some super important things to keep in mind.
– You should only update UI from the main thread. This can get you in subtle ways...
– NSNotifications will be received in the thread from which they are fired. So if you launch a thread and subscribe to a NSNotification to trigger a UI action, you should check what thread you're on when you get it. If it's not on the main thread use NSObject's performSelectorOnMainThread: withObject:waitUntilDone: to get it on the main thread.
– If you're doing some drawing into a non-ui context, I believe core graphics is now thread safe. (I believe CATiledLayer does some clever things because of this)
– Generally for view controllers, the only event loop you should think about is the one on the main thread. Think twice before making your own event loop on another thread.
If you are writing normal UIViewController code, you don't need to worry about thread-safety in iOS. In iOS, any message about UI should be running on the main thread.
If you don't perform some message in background by you self, normally, you don't have to worry about thread, in most situations, it will always be on the main thread.
P.S. Some Frameworks like Game Kit will some times perform messages in background, but it's not about UI and the document from Apple will warn you to make sure if the message is running on main thread.
The Concurrency Programming Guide can be helpful.

What can I do if two detached threads overlap each other? queue

I'm not very 'up' on multi-threading, but I've been using detachNewThreadSelector in a couple of places to access data in a database. Unfortunately, on slower devices the first request may still be happening when I call the second... Which naturally causes a crash because both are calling the same method (which is obviously not thread-safe).
What is the best way to go about sorting a bug like this? Can I somehow queue them so that the second thread doesn't start until the first one has finished?
Thanks!
You may want to have a look at NSOperation and NSOperationQueue which is an abstraction for a queue of tasks that can be run asynchronously from the main thread. If you want the NSOperationQueue to run just a NSOperation at a time (so to wait after the current task is compleate before firing the next one) you can just set the maxConcurrentOperationCount property of the queue to 1
To extend ranos answer a bit, be sure to add operations from the same thread because if you add several NSOperations from several threads, they will run concurrently, even though maxConcurrentOperationCount on NSOperationQueue is set to 1.

Difference between performSelectorInBackground and NSOperation Subclass

I have created one testing app for running deep counter loop. I run the loop function in background thread using performSelectorInBackground and also NSOperation subclass separately.
I am also using performSelectorOnMainThread to notify main thread within backgroundthread method and [NSNotificationCenter defaultCenter] postNotificationName within NSOperation subclass to notify main thread for updating UI.
Initially both the implementation giving me same result and i am able to update UI without having any problem. The only difference I found is the Thread count between two implementations.
The performSelectorInBackground implementation created one thread and got terminated after loop finished and my app thread count again goes to 1.
The NSOperation subclass implementation created two new threads and keep exists in the application and i can see 3 threads after loop got finished in main() function.
So, my question is why two threads created by NSOperation and why it didn't get terminated just like the first background thread implementation?
I am little bit confuse and unable to decide which implementation is best in-terms of performance and memory management.
It's likely the operation queue is keeping threads alive, waiting for new operations to appear.
You have to remember that the operation queue is designed to work efficiently with many operations, so creating and destroying threads for each operation is going to hurt performance. So what you are seeing is probably just the way the queue is designed to work by keeping a pool of threads alive.
Basically, as long as you are using the operation queue properly and according to the documentation I wouldn't worry about it.