异步改同步的场景
- 请求n个接口,几个接口无依赖关系,在都返回数据之后刷新UI或执行其他操作
- 请求n个接口,几个接口有依赖关系,在依次返回数据之后刷新UI或执行其他操作
- 一个有返回对象的方法,里边有异步操作获取要返回的对象或某一类型的值
场景一
请求n个接口,无依赖关系,在都返回数据之后刷新UI或执行其他操作
示例中写了四个接口方法和一个操作方法
1. 最简单的调用方式,依次调用接口方法,在最后一个接口方法中调用刷新UI操作。
- (void)viewDidLoad {
[super viewDidLoad];
[self methodA];
}
- (void)methodA{
[self methodA:^{
[self methodB];
}];
}
- (void)methodB{
[self methodB:^{
[self methodC];
}];
}
- (void)methodC{
[self methodC:^{
[self methodD];
}];
}
- (void)methodD{
[self methodD:^{
[self method];
}];
}
- (void)methodA:(void(^)(void))success_block{
dispatch_queue_t queue = dispatch_queue_create("com.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
sleep(4);
NSLog(@"执行了方法A");
if (success_block) {
success_block();
}
});
}
- (void)methodB:(void(^)(void))success_block{
dispatch_queue_t queue = dispatch_queue_create("com.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"执行了方法B");
if (success_block) {
success_block();
}
});
}
- (void)methodC:(void(^)(void))success_block{
dispatch_queue_t queue = dispatch_queue_create("com.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"执行了方法C");
if (success_block) {
success_block();
}
});
}
- (void)methodD:(void(^)(void))success_block{
dispatch_queue_t queue = dispatch_queue_create("com.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"执行了方法D");
if (success_block) {
success_block();
}
});
}
- (void)method{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"执行了方法:刷新UI或其他操作");
});
}
执行结果
执行了方法A
执行了方法B
执行了方法C
执行了方法D
执行了方法:刷新UI或其他操作
2. 用dispatch_group_t 调度组 dispatch_group_enter()和dispatch_group_leave()是成对出现的
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.queue", DISPATCH_QUEUE_SERIAL);
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
[self methodA:^{
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
[self methodB:^{
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
[self methodC:^{
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
[self methodD:^{
dispatch_group_leave(group);
}];
});
dispatch_group_notify(group, queue, ^{
[self method];
})
}
执行结果如下,刷新UI操作定是在最后,请求接口的四个方法顺序不定
执行了方法B
执行了方法C
执行了方法D
执行了方法A
执行了方法:刷新UI或其他操作
场景二
请求n个接口,几个接口有依赖关系,在依次返回数据之后刷新UI或执行其他操作
这里假设方法A需要方法B的值 方法B需要C的值
1.可以用最简单的方式,和场景一的1方式一样 直接方法套方法的去调用
2.dispatch_semaphore_t 信号量来控制请求顺序 dispatch_semaphore_signal()信号加1 dispatch_semaphore_wait()信号减1
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self methodC:^{
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self methodB:^{
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self methodA:^{
dispatch_semaphore_signal(semaphore);
}];
[self methodD:^{
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self method];
}
执行结果
2019-02-12 11:13:32.541273+0800 GCD_Demo[91206:10764077] 执行了方法C
2019-02-12 11:13:36.546541+0800 GCD_Demo[91206:10764077] 执行了方法B
2019-02-12 11:13:36.546991+0800 GCD_Demo[91206:10764077] 执行了方法A
2019-02-12 11:13:36.547034+0800 GCD_Demo[91206:10764081] 执行了方法D
2019-02-12 11:13:36.560470+0800 GCD_Demo[91206:10764026] 执行了方法:刷新UI或其他操作
场景三
一个有返回对象的方法,里边有异步操作获取要返回的对象或某一类型的值
1. 直接异步里边修改局部变量
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",[self nameStr]);//是需要获取异步得到的数值,以供同步来使用。
NSLog(@"next");
}
- (NSString *)nameStr{
__block NSString * nameStr = @"小红";
[self method:^(NSString *name) {
nameStr = name;
}];
return nameStr;
}
- (void)method:(void(^)(NSString * name))success_block{
dispatch_queue_t queue = dispatch_queue_create("com.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
if (success_block) {
success_block(@"小明");
}
});
}
运行结果可想而知,并没有改变局部变量
2019-02-12 11:36:45.800273+0800 GCD_Demo[92013:10799031] 小红
2019-02-12 11:36:45.800431+0800 GCD_Demo[92013:10799031] next
2. 用while循环阻塞线程 达到异步改同步的效果
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",[self nameStr]);
NSLog(@"next");
}
- (NSString *)nameStr{
NSString __block * nameStr = @"小红";
__block BOOL _sleep = YES;
[self method:^(NSString *name) {
nameStr = name;
NSLog(@"1");
_sleep = NO;
NSLog(@"3");
}];
while (_sleep) {
//while循环等待阻塞线程
}
NSLog(@"2");
return nameStr;
}
由打印结果可以实现了异步改同步
2019-02-20 09:48:39.490238+0800 GCD_Demo[12318:20531485] 1
2019-02-20 09:48:39.490351+0800 GCD_Demo[12318:20531435] 2
2019-02-20 09:48:39.490351+0800 GCD_Demo[12318:20531485] 3
2019-02-20 09:48:39.490439+0800 GCD_Demo[12318:20531435] 小明
2019-02-20 09:48:39.490501+0800 GCD_Demo[12318:20531435] next
不过,在多次运行比较结果可知2和3的顺序不定定。应该是while循环监听_sleep时的机制,_sleep变量改变时while是否开始新的一次轮询。
3. 用信号量控制 异步改同步 修改代码如下
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",[self nameStr]);//是需要获取异步得到的数值,以供同步来使用。
NSLog(@"next");
}
#pragma mark - 异步改同步
- (NSString *)nameStr{
__block NSString * nameStr = @"小红";
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self method:^(NSString *name) {
nameStr = name;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return nameStr;
}
运行结果如下,block内的修改局部变量并返回是成功的。
2019-02-12 11:34:42.340972+0800 GCD_Demo[91941:10796468] 小明
2019-02-12 11:34:42.341121+0800 GCD_Demo[91941:10796468] next
4. 利用dispatch_group_t 调度组 异步改同步 代码如下
- (NSString *)nameStr{
__block NSString * nameStr = @"小红";
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self method:^(NSString *name) {
nameStr = name;
dispatch_group_leave(group);
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
return nameStr;
}
运行结果如下,block内的修改局部变量并返回是成功的。
2019-02-12 17:26:53.044820+0800 GCD_Demo[1838:11137671] 小明
2019-02-12 17:26:53.044949+0800 GCD_Demo[1838:11137671] next
使用示例场景
1. AFNetworking 3.0中 AFURLSessionManager类中L645
通过引入信号量(dispatch_semaphore)的方式把NSURLSession的异步方法 getTasksWithCompletionHandler: 变成了同步方法
这里是把本来异步的getTasksWithCompletionHandler方法变成了同步的方式了,通过引入信号量的方式,等待异步方法获取到tasks,然后再返回。
- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
__block NSArray *tasks = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
、、、
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return tasks;
}
2.MJExtension中也有应用
+ (NSMutableArray *)mj_totalObjectsWithSelector:(SEL)selector key:(const char *)key
{
MJExtensionSemaphoreCreate
MJExtensionSemaphoreWait
NSMutableArray *array = [self classDictForKey:key][NSStringFromClass(self)];
if (array == nil) {
// 创建、存储
[self classDictForKey:key][NSStringFromClass(self)] = array = [NSMutableArray array];
if ([self respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
NSArray *subArray = [self performSelector:selector];
#pragma clang diagnostic pop
if (subArray) {
[array addObjectsFromArray:subArray];
}
}
[self mj_enumerateAllClasses:^(__unsafe_unretained Class c, BOOL *stop) {
NSArray *subArray = objc_getAssociatedObject(c, key);
[array addObjectsFromArray:subArray];
}];
}
MJExtensionSemaphoreSignal
return array;
}
#pragma mark - 公共方法
+ (NSMutableArray *)properties
{
NSMutableArray *cachedProperties = [self propertyDictForKey:&MJCachedPropertiesKey][NSStringFromClass(self)];
if (cachedProperties == nil) {
MJExtensionSemaphoreCreate
MJExtensionSemaphoreWait
if (cachedProperties == nil) {
cachedProperties = [NSMutableArray array];
[self mj_enumerateClasses:^(__unsafe_unretained Class c, BOOL *stop) {
// 1.获得所有的成员变量
unsigned int outCount = 0;
objc_property_t *properties = class_copyPropertyList(c, &outCount);
// 2.遍历每一个成员变量
for (unsigned int i = 0; i<outCount; i++) {
MJProperty *property = [MJProperty cachedPropertyWithProperty:properties[i]];
、、、
}
// 3.释放内存
free(properties);
}];
[self propertyDictForKey:&MJCachedPropertiesKey][NSStringFromClass(self)] = cachedProperties;
}
MJExtensionSemaphoreSignal
}
return cachedProperties;
}
另外说明的是,在MJExtension中信号量不只是用来异步改同步,把信号量当做锁来确保线程安全也是一个应用场景 这里仅仅示例两处 如下:
- (void)setPorpertyKeys:(NSArray *)propertyKeys forClass:(Class)c
{
if (propertyKeys.count == 0) return;
NSString *key = NSStringFromClass(c);
if (!key) return;
MJExtensionSemaphoreCreate
MJExtensionSemaphoreWait
self.propertyKeysDict[key] = propertyKeys;
MJExtensionSemaphoreSignal
}
+ (void)mj_setupObjectClassInArray:(MJObjectClassInArray)objectClassInArray
{
[self mj_setupBlockReturnValue:objectClassInArray key:&MJObjectClassInArrayKey];
MJExtensionSemaphoreCreate
MJExtensionSemaphoreWait
[[self propertyDictForKey:&MJCachedPropertiesKey] removeAllObjects];
MJExtensionSemaphoreSignal
}
MJExtension 宏注释
// 信号量
#define MJExtensionSemaphoreCreate \
static dispatch_semaphore_t signalSemaphore; \
static dispatch_once_t onceTokenSemaphore; \
dispatch_once(&onceTokenSemaphore, ^{ \
signalSemaphore = dispatch_semaphore_create(1); \
});
#define MJExtensionSemaphoreWait \
dispatch_semaphore_wait(signalSemaphore, DISPATCH_TIME_FOREVER);
#define MJExtensionSemaphoreSignal \
dispatch_semaphore_signal(signalSemaphore);