Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / iPhone

iOS 4 in Action - Fetching Events with Grand Central Dispatch (GCD)

4.00/5 (1 vote)
26 May 2011CPOL3 min read 19K  
A chapter excerpt from iOS 4 in Action- Fetching events with Grand Central Dispatch (GCD)
image002.jpgiOS 4 in Action
Developing iPhone & iPad Apps

By Jocelyn Harrington, Brandon Trebitowski, Christopher Allen, and Shannon Appelcline

Though multicore is not available on iOS devices, Grand Central Dispatch helps the application to run faster, more efficiently, and asynchronously. In this article, based on chapter 16 of iOS 4 in Action, the authors show you how GCD is used to fetch events.

To save 35% on your next purchase use Promotional Code jharrington1635 when you check out at www.manning.com.

You may also be interested in…

Grand Central Dispatch (GCD) was available on Mac OS as comprehensive improvements to support concurrent code execution on multicore hardware technology. Now, it’s available on iOS 4 as a C API. Though multicore is not available on iOS devices, GCD helps the application to run faster, more efficiently, and asynchronously. You can find more reference on Concurrency Programming Guide from the iOS developer website. Let’s look at GCD and use it to fetch events.

How does it work?

GCD is available to any application and there is no need to add in any other framework. You can imagine that you have queues of operations and each queue is running in its own thread separately by the system. You don’t have to worry about when to run the time-consuming operations. The system will take care of the order and make sure that the queue’s operations get done.

In order to keep the application running responsively, the key concept is not to block the main thread. Throw a time-consuming task, such as fetching a list of events from the Calendar’s database or downloading an image file from the Internet, to the background thread. Then, update the UI after the work in the background is done, and the data is ready to display.

How do you accomplish this task with GCD? It turns out, it’s pretty easy. Simply, call the method dispatch_async() to submit a queue of operations (a block of code) to the main queue and execute the task on a dispatch queue asynchronously, and then tell the system to update the UI.

The definition for dispatch_async() is listed as:

void dispatch_async( dispatch_queue_t queue,
                  dispatch_block_t block
);

How do we create a queue or get the main queue? Here are some common methods related to GCD:

  • Creating a queue:
    dispatch_queue_t
    dispatch_queue_create(const char *label, NULL); 
  • Releasing a queue:
    void
    dispatch_release(dispatch_queue_t);
  • Getting the main queue:
    dispatch_queue_t
    dispatch_get_main_queue();

Please don’t forget to release the queue when it is created with method dispatch_queue_create().

With GCD and blocks in hand, let’s see how to create a queue for the fetching events operations and let the system decide when to run this queue, and then update the UI in the main thread.

Fetching Events with GCD

Let’s use the GCD and blocks to fetch the whole month of events and update the table view display.

Listing 1 Fetching events with GCD

-(void)fetchEventsForNextMonth {
    NSDate *startDate = [NSDate date];
    NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:60*60*24*30];
    NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:eventStore.calendars]; 
    dispatch_queue_t fetching_queue= 
dispatch_queue_create("Fetching events", NULL);#1
    dispatch_async(fetching_queue, ^{                      #2
           NSArray *eventList = 
[self.eventStore eventsMatchingPredicate:predicate];
           dispatch_async(dispatch_get_main_queue(), ^{    #3
                  [self.events addObjectsFromArray:eventList];
                  [self.tableView reloadData];
           });
    });
dispatch_release(fetching_queue); #4
}
#1 Defines a custom queue
#2 Fetches events 
#3 Updates UI
#4 Releases queue

In listing 1, we first create a custom queue (#1). The GCD function starts (#2). The block of operations will first execute the custom task to fetch events from the Calendar’s database on the dispatch queue. When the eventList array is ready, we want to update the table view’s UI with the new data on the main queue dispatch. The block (#3) first updates the events array and then reloads the table view’s data. Finally, don’t forget to release the queue (#4). Simply follow the design flow; GCD will automatically finish the task and provide a quick response asynchronously.

As you can see from the example, with a few lines of code, you managed to perform a task in the background and update the UI when the new data is ready. That’s the power of GCD and blocks.

Summary

The Event Kit framework provides an interface for accessing calendar events on a user’s device. You can use this framework to get existing events and add new events to the user’s calendar. With GCD, the application’s performance is improved significantly, especially when fetching events from Calendar’s database asynchronously.

Here are some other Manning titles you might be interested in:

image003.jpg

Objective-C for the iPhone
Christopher K. Fairbairn and Collin Ruffenach

image004.jpg

iPhone in Practice
Bear P. Cahill

image005.jpg

Unlocking Android, Second Edition
W. Frank Ableson and Robi Sen

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)