iOS 知识小集(5)

异步方法封装成同步

  • 使用派发组dispatch_group
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

- (NSInteger)methodSync {
NSLog(@"methodSync 开始");

__block NSInteger result = 0;

dispatch_group_t group = dispatch_group_create();

dispatch_group_enter(group);

[self methodAsync:^(NSInteger value) {

result = value;

dispatch_group_leave(group);

}];

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

NSLog(@"methodSync 结束 result:%ld", (long)result);

return result;
}
  • (推荐):使用信号量dispatch_semaphore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (NSInteger)methodSync {
NSLog(@"methodSync 开始");

__block NSInteger result = 0;

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[self methodAsync:^(NSInteger value) {

result = value;

dispatch_semaphore_signal(sema);

}];
// 这里本来同步方法会立即返回,但信号量=0使得线程阻塞
// 当异步方法回调之后,发送信号,信号量变为1,这里的阻塞将被解除,从而返回正确的结果

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

NSLog(@"methodSync 结束 result:%ld", (long)result);

return result;
}