舉例:比如A、B兩個請求,B必須等待A完成才執(zhí)行波岛。像這種情況的話很多人都在A請求完成的回調(diào)里面寫,這樣是可以的音半,但是要實現(xiàn)同步的話還有兩種方法则拷,一個是 GCD 里面的 barrier 函數(shù),另外一個是 GCD 里面信號量的方式曹鸠,我覺得信號量的方式是更靈活的處理煌茬,代碼入下:
dispatch_semaphore_t semap = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[AFNetworking requestWithURLString:BASEURLWITH(@"login")
parameters:@{@"email":@"fucc@gmail.com",
@"password":@"xxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"a完成");
dispatch_semaphore_signal(semap);
} failure:^(NSError *error) {
NSLog(@"a完成,但是失敗了");
dispatch_semaphore_signal(semap);
}];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//等待信號30s彻桃,如果超過30s的話坛善,則進入 if 方法,否則就進入 else 方法
//超時返回1
if (dispatch_semaphore_wait(semap, dispatch_time(DISPATCH_TIME_NOW,
30 * NSEC_PER_SEC)))
{
//處理超時
//也可以把超時時間設置成forever,會一直等待直到收到信號
}
//不超時返回0
else {
[AFNetworking requestWithURLString:BASEURLWITH(@"login")
parameters:@{@"email":@"fucc@gmail.com",
@"password":@"xxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"b完成");
} failure:^(NSError *error) {
NSLog(@"b完成邻眷,但是失敗了");
}];
}
});
舉例:A眠屎、B、C三個請求肆饶,ABC都完成改衩,并且成功再執(zhí)行下一個動作。
錯誤示范:int i = 0驯镊,A 完成 i++,B 完成 i++, C完成 i++,然后在A葫督、B、C三個請求的成功回調(diào)里板惑,都進行判斷 i==3橄镜,這樣會出錯的原因是,3個請求同時完成的話冯乘,i = 1蛉鹿。
正確示范代碼入下:
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_enter(dispatchGroup);
NSLog(@"1");
[AFNetworking requestWithURLString:BASEURLWITH(@"login1")
parameters:@{@"email":@"fucc1@gmail.com",
@"password":@"xxxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"1完成");
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
NSLog(@"%@",error);
}];
dispatch_group_enter(dispatchGroup);
NSLog(@"2");
[AFNetworking requestWithURLString:BASEURLWITH(@"login2")
parameters:@{@"email":@"fucc2@gmail.com",
@"password":@"xxxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"2完成");
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
NSLog(@"%@",error);
}];
dispatch_group_enter(dispatchGroup);
NSLog(@"3");
[AFNetworking requestWithURLString:BASEURLWITH(@"login3")
parameters:@{@"email":@"fucc3@gmail.com",
@"password":@"xxxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"3完成");
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
NSLog(@"%@",error);
}];
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"3個請求完成");
});