/Async

Syntactic sugar in Objective-C for asynchronous dispatches in Grand Central Dispatch

Primary LanguageObjective-C

Async

Syntactic sugar in Objective-C for asynchronous dispatches in Grand Central Dispatch(GCD)

Note:Here is the Async in Swift.

Async sugar looks like this:

[[Async main:^{								
        NSLog(@"===>>> This is run on the main queue");
}] background:^{
        NSLog(@"===>>> This is run on the background queue");
}];

Instead of the familiar syntax for GCD:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
    NSLog(@"===>>> This is run on the background queue");
    
    dispatch_async(dispatch_get_main_queue(), {
        NSLog(@"===>>> This is run on the main queue, after the previous block");
    })
})

Benefits

  1. Less verbose code
  2. Less code indentation

Things you can do

Supports the modern queue classes:

[GCD mainQueue]
[GCD userInteractiveQueue]
[GCD userInitiatedQueue]
[GCD utilityQueue]
[GCD backgroundQueue]

Chain as many blocks as you want:

[[[[[Async main:^{
    // 1
}] background:^{
    // 2
}] utility:^{
    // 3
}] userInteractive:^{
   // 4
}] main:^{
   // 5
}];

Store reference for later chaining:

Async *backgroundBlock = [Async background:^{
    NSLog(@"===>>> This is run on the background queue");
}];

// Run other code here...

// Chain to reference
[backgroundBlock main:^{
    NSLog(@"===>>> This is run on the %@, after the previous block", [NSThread currentThread]);
}];