屏幕横竖屏

iOS AFNetworking中使用“信号量”无返回结果

2022-05-12  本文已影响0人  心猿意码_

示例如下:

- (void)viewDidLoad {
  NSLog(@"开始====%@",@"A");
  [self loadListMenuWithFinishMark:@"A"];
  NSLog(@"开始====%@",@"B");
  [self loadListMenuWithFinishMark:@"B"];
  NSLog(@"开始====%@",@"C");
  [self loadListMenuWithFinishMark:@"C"];
}

- (void)loadListMenuWithFinishMark:(NSString *)mark{
    // 创建信号量
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSString *urlString = @"http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
    [[AFHTTPSessionManager manager] GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 发送信号 (+ 1)
        dispatch_semaphore_signal(sema);
        NSLog(@"结束======%@",mark);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_semaphore_signal(sema);
        NSLog(@"结束======%@", mark);
    }];
    // 等待signal执行+1后(>0),才执行wait后的业务
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

打印结果:

2022-05-12 10:35:50.871154+0800 SemaphoreDemo[12896:3290528] 开始====A

原因是:
如果在主线程运行以上代码,会发现没有结果输出;这是因为AFNetworking回调默认是主线程,这样dispatch_semaphore_waitdispatch_semaphore_signal在同一个线程,这样就死锁了。
所以以上代码需要放在异步线程执行如下:

- (void)viewDidLoad {
  dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"开始====%@",@"A");
        [self loadListMenuWithFinishMark:@"A"];
        NSLog(@"开始====%@",@"B");
        [self loadListMenuWithFinishMark:@"B"];
        NSLog(@"开始====%@",@"C");
        [self loadListMenuWithFinishMark:@"C"];
    });
}

- (void)loadListMenuWithFinishMark:(NSString *)mark{
    // 创建信号量
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSString *urlString = @"http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
    [[AFHTTPSessionManager manager] GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 发送信号 (+ 1)
        dispatch_semaphore_signal(sema);
        NSLog(@"结束======%@",mark);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_semaphore_signal(sema);
        NSLog(@"结束======%@", mark);
    }];
    // 等待signal执行+1后(>0),才执行wait后的业务
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

打印结果:

2022-05-12 10:29:55.555207+0800 SemaphoreDemo[12269:3284921] 开始====A
2022-05-12 10:29:55.706748+0800 SemaphoreDemo[12269:3284782] 结束======A
2022-05-12 10:29:55.706758+0800 SemaphoreDemo[12269:3284921] 开始====B
2022-05-12 10:29:55.712722+0800 SemaphoreDemo[12269:3284782] 结束======B
2022-05-12 10:29:55.712728+0800 SemaphoreDemo[12269:3284921] 开始====C
2022-05-12 10:29:55.715101+0800 SemaphoreDemo[12269:3284782] 结束======C

走过路过,点个👍🏻在走哈!!~~

上一篇下一篇

猜你喜欢

热点阅读