情景

顺序执行操作,但只有异步调用方法可供使用。

回调地狱书写不美观,容易出错切难以维护。

方案

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) {

// TODO: onSuccess

if(_nextAction != nil)
{
_nextAction();
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// TODO: onFailure
}];
}

@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 = [[RequestBase alloc] init];
request.nextAction = action2;
[request startRequest];
};
action2 = ^(){
RequestBase *request = [[RequestBase alloc] init];
request.nextAction = action3;
[request startRequest];
};
action3 = ^(){
RequestBase *request = [[RequestBase alloc] init];
[request startRequest];
};

action1();