GCDObjC
GCDObjC is an Objective-C wrapper for the most commonly used features of Grand Central Dispatch. It has four main aims:
- Organize the flat C API into appropriate classes.
- Use intention-revealing names to distinguish between synchronous and asynchronous functions.
- Use more convenient arguments such as time intervals.
- Add convenience methods.
A Swift port is at GCDSwift.
Usage
GCDObjC requires ARC and iOS 6.0. (Prior to 6.0, dispatch objects were not considered Objective-C objects, and therefore required manual memory management.)
GCDObjC.h is the only header file that needs to be imported.
For usage examples, see GCDObjCTests.m.
Install via CocoaPods:
pod "GCDObjC"
GCDQueue
Queues are implemented in the GCDQueue class.
- convenience accessors for global queues
+ (GCDQueue *)mainQueue;
+ (GCDQueue *)globalQueue;
+ (GCDQueue *)highPriorityGlobalQueue;
+ (GCDQueue *)lowPriorityGlobalQueue;
+ (GCDQueue *)backgroundPriorityGlobalQueue;
- testing the current execution context
+ (BOOL)isMainQueue;
- creating serial and concurrent queues
- (instancetype)initSerial;
- (instancetype)initConcurrent;
- queueing blocks for asynchronous execution
- (void)queueBlock:(dispatch_block_t)block;
- (void)queueBlock:(dispatch_block_t)block afterDelay:(double)seconds;
- (void)queueBlock:(dispatch_block_t)block inGroup:(GCDGroup *)group;
- queueing blocks for synchronous execution
- (void)queueAndAwaitBlock:(dispatch_block_t)block;
- (void)queueAndAwaitBlock:(void (^)(size_t))block iterationCount:(size_t)count;
- queueing barrier blocks for synchronous or asynchronous execution
- (void)queueBarrierBlock:(dispatch_block_t)block;
- (void)queueAndAwaitBarrierBlock:(dispatch_block_t)block;
- queueing notify blocks on groups
- (void)queueNotifyBlock:(dispatch_block_t)block inGroup:(GCDGroup *)group;
- suspending and resuming a queue
- (void)suspend;
- (void)resume;
- associating context data with a key
- (void *)contextForKey:(const void *)key;
- (void)setContext:(void *)context forKey:(const void *)key;
GCDSemaphore
Semaphores are implemented in the GCDSemaphore class.
- creating semaphores
- (instancetype)init;
- (instancetype)initWithValue:(long)value;
- signaling and waiting on a semaphore
- (BOOL)signal;
- (void)wait;
- (BOOL)wait:(double)seconds;
GCDGroup
Groups are implemented in the GCDGroup class.
- creating groups
- (instancetype)init;
- entering and leaving a group
- (void)enter;
- (void)leave;
- waiting on completion of a group
- (void)wait;
- (BOOL)wait:(double)seconds;
Macros
Two macros are provided for wrapping dispatch_once() calls.
- executing a block only once: GCDExecOnce(block)
for (int i = 0; i < 10; ++i) {
GCDExecOnce(^{ NSLog(@"This will only be logged once."); });
}
- creating a singleton instance of a class: GCDSharedInstance(block)
+ (instancetype)sharedInstance {
GCDSharedInstance(^{ return [self new]; });
}
The block supplied to GCDSharedInstance() must return an instance of the desired class.