Another approach to this problem might be: create a helper object for the async task and copy the completion block when the task is called. Call the completion block using the delegate methods as soon as the async task is completed. As a result, we could perform the tasks in the following order:
FSTask *taskA = [FSTask taskWithName:@"Task A"]; FSAsyncTask *taskB = [FSAsyncTask asyncTaskWithName:@"Task B"]; FSTask *taskC = [FSTask taskWithName:@"Task C"]; [taskA performTaskWithCompletionBlock:^ (NSString *result) { NSLog(@"%@", result); [taskB performTaskWithCompletionBlock:^ (NSString *result) { NSLog(@"%@", result); [taskC performTaskWithCompletionBlock:^ (NSString *result) { NSLog(@"%@", result); }]; }]; }];
So how is this achieved? Well, look at the task objects below ...
FSTask.m - synchronous work on the main thread ...
@interface FSTask () @property (nonatomic, copy) NSString *name; @end @implementation FSTask @synthesize name = _name; + (FSTask *)taskWithName:(NSString *)name { FSTask *task = [[FSTask alloc] init]; if (task) { task.name = name; } return task; } - (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block { NSString *message = [NSString stringWithFormat:@"%@: doing work on main thread ...", _name]; NSLog(@"%@", message); if (block) { NSString *result = [NSString stringWithFormat:@"%@: result", _name]; block(result); } } @end
FSAsyncTask.m - asynchronous work on a background thread ...
@interface FSAsyncTask () @property (nonatomic, copy) void (^block)(NSString *taskResult); @property (nonatomic, copy) NSString *name; - (void)performAsyncTask; @end @implementation FSAsyncTask @synthesize block = _block; @synthesize name = _name; + (FSAsyncTask *)asyncTaskWithName:(NSString *)name { FSAsyncTask *task = [[FSAsyncTask alloc] init]; if (task) { task.name = name; } return task; } - (void)performTaskWithCompletionBlock:(void (^)(NSString *taskResult))block { self.block = block;
source share