![](https://csdnimg.cn/release/download_crawler_static/10269408/bg14.jpg)
7
Control-drag from the View Controller icon in the Document Outline to connect
the view controller’s two outlets (i.e., the startButton and resultsTextView instance
variables) to the button and the text view.
Next, Control-drag from the button to the View Controller, release the mouse, and
select the doWork() method in the pop-up so that it’s called when the button is pressed.
Finally, select the text view, use the Attributes Inspector to uncheck the Editable check
box (it’s in the upper-right corner), and delete the default text from the text view.
Save your work, and then select Run. Your app should start up, and pressing the
button will make it work for about ten seconds (the sum of all those sleep amounts)
before showing you the results. During your wait, you'll see that the Start Working button
fades visibly, never turning back to its normal color until the “work” is done. Also, until
the work is complete, the application’s view is unresponsive. Tapping anywhere on the
screen or rotating the device has no effect. In fact, the only way you can interact with
your application during this time is by tapping the home button to switch away from it.
This is exactly the state of affairs we want to avoid.
Threading Basics
Before we start implementing solutions, let’s go over some concurrency basics. This is
far from a complete description of threading in iOS or threading in general. I just want
to explain enough for you to understand what we’re doing in this chapter. Most modern
operating systems (including, of course, iOS) support the notion of threads of execution.
Each process can contain multiple threads, which all run concurrently. If there’s just one
processor core, the operating system will switch between all executing threads, much
like it switches between all executing processes. If more than one core is available, the
threads will be distributed among them, just as processes are.
All threads in a process share the same executable program code and the same
global data. Each thread can also have some data that is exclusive to the thread. Threads
can make use of a special structure called a mutex (short for mutual exclusion) or a
lock, which can ensure that a particular chunk of code can’t be run by multiple threads
at once. This is useful for ensuring correct outcomes when multiple threads access the
same data simultaneously, by locking out other threads when one thread is updating a
value (in what’s called a critical section of your code).
CHAPTER 1 MULTITHREADED PROGRAMMING USING GRAND CENTRAL DISPATCH