ios 想问一个很简单的异步问题

[manager POST:@"https://www.baidu.com" parameters:@{} success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"ok1"); 
   }       

NSLog(@"ok2");

很明显这段代码 如果打印的话 肯定是:先ok2 再ok1

有没有什么办法先ok1 再 ok2

当然不能把 NSLog(@"ok2");这句放到异步代码块之后的情况下 达到上述要求

阅读 3.6k
3 个回答

用 NSRunLoop()

1.runloop

runloop = YES;  

[manager POST:@"https://www.baidu.com" parameters:@{} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"ok1"); 
       runloop = NO;
   })];

while (runloop)
 {  
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];  
 }
  
NSLog(@"ok2");  

2.GCD group

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, queue , ^{
    dispatch_group_enter(group);
    [manager POST:@"https://www.baidu.com" parameters:@{} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"ok1"); 
        dispatch_group_leave(group);
   })];
});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"ok2");   
 });

用GCD的同步方法。。

推荐问题
宣传栏