NSURLConnection代理的相關細節

NSURLConnection代理在子線程運行

NSURLConnection的代理默認是在主線程運行的網絡

-(void)viewDidLoad
{
    NSString *strUrl = @"";
    
    strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
    [con setDelegateQueue:[[NSOperationQueue alloc] init]];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", [NSThread currentThread]);
}

輸出:{number = 1, name = main}

設置NSURLConnection的代理在子線程運行,須要執行 [con setDelegateQueue] 方法async

-(void)viewDidLoad
{
    NSString *strUrl = @";
    
    strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
    [con setDelegateQueue:[[NSOperationQueue alloc] init]];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", [NSThread currentThread]);
}

輸出:{number = 3, name = (null)}

注:調用[con setDelegateQueue]方法,參數不能傳遞主線程,否則會卡死線程;oop

在子線程中執行NSURLConnection網絡請求

-(void)viewDidLoad
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *strUrl = @"";
        
        strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSURL *url = [NSURL URLWithString:strUrl];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    });
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", [NSThread currentThread]);
}

將網絡請求放到子線程中執行,網絡請求操做是不會執行的.這是由於NSURLConnection須要在RunLoop中執行,NSURLConnection 的start方法的註釋中寫到:若是在調用網絡請求時沒有指定RunLoop或operation queue,connection會被指定在當前線程的RunLoop的default模式中運行;url

-(void)viewDidLoad
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *strUrl = @"";
        
        strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSURL *url = [NSURL URLWithString:strUrl];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    });
    
    //讓當前線程的RunLoop運行起來
    [[NSRunLoop currentRunLoop] run]; 
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@", [NSThread currentThread]);
}
相關文章
相關標籤/搜索