sendAsynchronousRequest方法将在块外部代码之前执行块代码

时间:2014-07-25 05:42:40

标签: ios objective-c nsurlconnection

当我使用sendAsynchronousRequest方法时,此方法内部块将在外部代码执行后执行?

__block NSDictionary *dict;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
    {
        NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode];
        NSLog(@"httpStatus inside block:%d",httpStatus);
        if ([data length]>0 && connectionError==nil)
        {
            dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];
        }
        else if (connectionError)
        {
            UIAlertView *alt=[[UIAlertView alloc] initWithTitle:@"Error" message:[connectionError localizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alt show];
        }
    }];

return dict;//it will return null because it will run before execute inner block of sendAsynchronousRequest

2 个答案:

答案 0 :(得分:0)

异步请求始终在网络线程中运行。 你的[NSOperationQueue mainQueue]意味着block-callback将在mainQueue中安排。 如果您想等到请求完成,您可以使用同步请求,或使用信号量来阻止当前线程。

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;

但注意这种方式请求将阻止当前线程。使用这种方式时要小心。

答案 1 :(得分:0)

你应该使用块方法

首先定义一个块

       typedef void (^OnComplate) (NSDictionary * dict);
- (void)viewDidLoad{
    [self getDataWithBlokc:^(NSDictionary *dict) {
        NSLog(@"%@",dict);
    }];
}

使用以下方法

-(void)getDataWithBlokc:(OnComplate)block{
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode];
         NSLog(@"httpStatus inside block:%d",httpStatus);
         if ([data length]>0 && connectionError==nil)
         {
            NSDictionary* dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];

             block(dict);
         }
         else if (connectionError)
         {
             UIAlertView *alt=[[UIAlertView alloc] initWithTitle:@"Error" message:[connectionError localizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
             [alt show];
         }
     }];
}