博客> OC-异步顺序加载
OC-异步顺序加载
2019-10-13 22:51 评论:0 阅读:1758 小李aa
block

前言

实际开发过程中,有可能会用到顺序加载异步的需求,比如先掉A接口,成功之后再掉B接口,再掉C接口,当然你在block里面嵌套也能实现,那么如果这个数量是很多呢,这里就变成回调地狱了,可以百度下这个。

解决办法

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

dispatch_async(dispatch_get_global_queue(0, 0), ^{

    [self logWithBlock:^(NSString *name) {

        NSLog(@"1%@",name);

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            dispatch_semaphore_signal(semaphore);

        });         
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    [self logWithBlock:^(NSString *name) {

        NSLog(@"2%@",name);

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            dispatch_semaphore_signal(semaphore);

        });
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    [self logWithBlock:^(NSString *name) {

        NSLog(@"3%@",name);

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            dispatch_semaphore_signal(semaphore);

        });
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    [self logWithBlock:^(NSString *name) {

        NSLog(@"4%@",name);

        dispatch_semaphore_signal(semaphore);

    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    NSLog(@"完毕");
});

-方法

-(void)logWithBlock:(void(^)(NSString *name))block{ block(@"===="); }

输出

 CFE40181-64E3-457C-B65E-A803580B5CBD.png

实现原理

发射信号量,设置无限时去等待,在这里很关键一点,这个等待会阻塞线程,所以切记不要在主线程里做这样得事情。

收藏
6
sina weixin mail 回到顶部