//Header File
typedef void (^TaskBlock)(void);
typedef void (^TaskCompletedBlock)(void);
@interface FCTaskManager : NSObject
-(void)performUITask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock;
-(void)performBackgroundTask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock;
@end
//Implementation
#import "FCTaskManager.h"
@implementation FCTaskManager
-(void)performUITask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock {
dispatch_async( dispatch_get_main_queue(), ^{
@autoreleasepool {
taskBlock();
dispatch_async( dispatch_get_main_queue(), ^{
taskCompletedBlock();
});
}
});
}
-(void)performBackgroundTask:(TaskBlock)taskBlock completionBlock:(TaskCompletedBlock)taskCompletedBlock {
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@autoreleasepool {
taskBlock();
dispatch_async( dispatch_get_main_queue(), ^{
taskCompletedBlock();
});
}
});
}
@end
Then I can use the task manager like so:
-(void)viewDidLoad {
[super viewDidLoad];
//Create taskManager
taskManager = [[FCTaskManager alloc] init];
//Create UIViews, etc WITHOUT blocking main queue
[taskManager performUITask:^{
button = [[UIButton alloc] initWithFrame:CGRectMake(30, 30, 300, 300)];
[button setBackgroundColor:[UIColor redColor]];
[button setTitle:@"Working" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
} completionBlock:^{
NSLog(@"CREATED BUTTON");
[self.view addSubview:button];
}];
}
No comments:
Post a Comment