Skip to content

Instantly share code, notes, and snippets.

@shyambhat
Created November 24, 2014 14:42
Show Gist options
  • Save shyambhat/fab5b0da84d2a893f9ad to your computer and use it in GitHub Desktop.
Save shyambhat/fab5b0da84d2a893f9ad to your computer and use it in GitHub Desktop.
Clean Objective C helper methods to perform background tasks and perform completion on main thread.
#import <Foundation/Foundation.h>
@interface GCDManager : NSObject
+ (void)performBackgroundTask:(void (^)())block withCompletion:(void (^)())completion;
+ (void)performHighPriorityBackgroundTask:(void (^)())block withCompletion:(void (^)())completion;
+ (void)performLowPriorityBackgroundTask:(void (^)())block withCompletion:(void (^)())completion;
@end
#import "GCDManager.h"
@implementation GCDManager
+ (void)performBackgroundTask:(void (^)())block withCompletion:(void (^)())completion
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
block();
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
});
}
+ (void)performHighPriorityBackgroundTask:(void (^)())block withCompletion:(void (^)())completion
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
block();
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
});
}
+ (void)performLowPriorityBackgroundTask:(void (^)())block withCompletion:(void (^)())completion
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
block();
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment