情景
顺序执行操作,但只有异步调用方法可供使用。
回调地狱书写不美观,容易出错切难以维护。
方案
以AFNetWorking
为例,做一个简单的链式封装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| typedef void (^NextAction)();
@interface RequestBase : NSObject @property (nonatomic, copy) NextAction nextAction; @end
@implementation RequestBase
- (void)startRequest { AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager POST:_url parameters:_parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if(_nextAction != nil) { _nextAction(); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }]; }
@end
|
调用范例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| __block NextAction action1, action2, action3; action1 = ^(){ RequestBase *request = ; request.nextAction = action2; ; }; action2 = ^(){ RequestBase *request = ; request.nextAction = action3; ; }; action3 = ^(){ RequestBase *request = ; ; };
action1();
|