Skip to content

Instantly share code, notes, and snippets.

@bobgodwinx
Last active October 26, 2015 14:28
Show Gist options
  • Save bobgodwinx/33346efc5f378b2f45b3 to your computer and use it in GitHub Desktop.
Save bobgodwinx/33346efc5f378b2f45b3 to your computer and use it in GitHub Desktop.
dispatch_queue_t for concurrent use.
@interface className()
//create a property as dispatch_queue_t
@property (nonatomic) dispatch_queue_t concurrentQueue;
@end
@implementation className
//implement a lazy initializer
- (dispatch_queue_t)concurrentQueue
{
static dispatch_once_t __dispatchToken = 0;
const char *queueAddress = "com.company.domain.concurrent";
dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_CONCURRENT, QOS_CLASS_USER_INITIATED, 2);
/**
* the trick goes here to declear it as [id] so it could be dispatched_once
* meaning we don't create it over and over again if we need to do multiple dispatch_async
*/
static id queue;
dispatch_once(&__dispatchToken, ^{
queue = dispatch_queue_create(queueAddress, attr);
});
return queue;
}
//Usage
- (void)performingSeriesOfTaskMethodName
{
__weak typeof(self)weakSelf = self;
dispatch_async(self.concurrentQueue, ^{
__strong typeof(weakSelf)strongSelf = weakSelf;
[strongSelf runYourMethodsInSideTheBlock];
//Always remember to update the main queue after you long task
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment