Grand Central Dispatch samples

Posted by Daniel Vela on August 4, 2011

You can use GCD for thread substitutions. It needs blocks.

Example of use:

 - (void)doTimeConsumingOperation:(id)operation {  
    dispatch_queue_t queue;  
    queue = dispatch_queue_create("com.example.operation",NULL);  
       [operation doOperation]; // Main op.  

You can use dispatch_sync instead dispatch_async for locked code execution.

Another sample of code is this way to perform a delayed selector on an object:

 - (void)doLaterOperation:(id)operation {  
      dispatch_time_t delay;  
      delay = dispatch_time(DISPATCH_TIME_NOW, 50000 /* nanoseconds */);  
           [operation doOperation]; // Main op.  

Finally other fine use of GCD is for creating safe singleton objects:

 +(MyClass *) sharedInstance {  
      static dispatch_once_t predicate;  
      static MyClass *shared = nil;  
      dispatch_once(&predicate, ^{  
          shared = [[MyClass alloc] init];  
      return shared;  

With dispatch_once the code only will be executed one and only one time.

Available in iOS 4.0 and later.
Available in Mac OS X v10.6 and later.