Block objects, together with Grand Central Dispatch (GCD), create a harmonious environment in which you can deliver high-performance multithreaded apps in iOS and Mac OS X. What’s so special about block objects and GCD, you might ask? It’s simple: no more threads! All you have to do is to put your code in block objects and ask GCD to take care of the execution of that code for you.
Block objects in Objective-C are what the programming field calls first-class objects. This means you can build code dynamically, pass a block object to a method as a parameter, and return a block object from a method. All of these things make it easier to choose what you want to do at runtime and change the activity of a program. In particular, block objects can be run in individual threads by GCD. Being Objective-C objects, block objects can be treated like any other object: you can retain them, release them, and so forth. Block objects can also be called closures.
Note: Block objects are sometimes referred to as closures.
Constructing block objects is similar to constructing traditional C functions. Block objects can have return values and can accept parameters. Block objects can be defined inline or treated as a separate block of code, similar to a C function. When created inline, the scope of variables accessible to block objects is considerably different from when a block object is implemented as a separate block of code.
GCD works with block objects. When performing tasks with GCD, you can pass a block object whose code can get executed synchronously or asynchronously, depending on which methods you use in GCD. Thus, you can create a block object that is responsible for downloading a URL passed to it as a parameter. That single block object can then be used in various places in your app synchronously or asynchronously, depending on how you would like to run it. You don’t have to make the block object synchronous or asynchronous per se; you will simply call it with synchronous or asynchronous GCD methods and the block object will just work.
Block objects are quite new to programmers writing iOS and OS X apps. In fact, block objects are not as popular as threads yet, perhaps because their syntax is a bit different from pure Objective-C methods and more complicated. Nonetheless, block objects are enormously powerful and Apple is making a big push toward incorporating them into Apple libraries. You can already see these additions in classes such as
NSMutableArray, where programmers can sort the array using a block object.Wouldn't it be great to take advantage of multicore processors without having to manage threads? This concise book shows you how to use Apple's Grand Central Dispatch (GCD) to simplify programming for multiple cores on iOS devices and Mac OS X. If you know how to program with Cocoa or Cocoa Touch, this guide will get you started with GCD right away, with many examples to help you write high-performing multithreaded apps.




Help






