標籤:json 開發人員 imm source 設定 microsoft iat new ini
(1)兩種為NSURLConnection設定代理方式的區別
//第一種設定方式: //通過該方法設定代理,會自動的發送請求 // [[NSURLConnection alloc]initWithRequest:request delegate:self]; //第二種設定方式: //設定代理,startImmediately為NO的時候,該方法不會自動發送請求 NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO]; //手動通過代碼的方式來發送請求 //注意該方法內部會自動的把connect添加到當前線程的RunLoop中在預設模式下執行 [connect start];
(2)如何控制代理方法在哪個線程調用
//說明:預設情況下,代理方法會在主線程中進行調用(為了方便開發人員拿到資料後處理一些重新整理UI的操作不需要考慮到線程間通訊) //設定代理方法的執行隊列 [connect setDelegateQueue:[[NSOperationQueue alloc]init]];
(3)開子線程發送網路請求的注意點,適用於自動發送網路請求模式
//在子線程中發送網路請求-調用startf方法發送-(void)createNewThreadSendConnect1{ //1.建立一個非主隊列 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //2.封裝操作,並把任務添加到隊列中執行 [queue addOperationWithBlock:^{ NSLog(@"%@",[NSThread currentThread]); //2-1.確定請求路徑 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=dd&pwd=ww&type=JSON"]; //2-2.建立請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //2-3.使用NSURLConnection設定代理,發送網路請求 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES]; //2-4.設定代理方法在哪個隊列中執行,如果是非主隊列,那麼代理方法將再子線程中執行 [connection setDelegateQueue:[[NSOperationQueue alloc]init]]; //2-5.發送網路請求 //注意:start方法內部會把當前的connect對象作為一個source添加到當前線程對應的runloop中 //區別在於,如果調用start方法開發送網路請求,那麼再添加source的過程中,如果當前runloop不存在 //那麼該方法內部會自動建立一個當前線程對應的runloop,並啟動。 [connection start]; }];}//在子線程中發送網路請求-自動發送網路請求-(void)createNewThreadSendConnect2{ NSLog(@"-----"); //1.建立一個非主隊列 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; //2.封裝操作,並把任務添加到隊列中執行 [queue addOperationWithBlock:^{ //2-1.確定請求路徑 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=dd&pwd=ww&type=JSON"]; //2-2.建立請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //2-3.使用NSURLConnection設定代理,發送網路請求 //注意:該方法內部雖然會把connection添加到runloop,但是如果當前的runloop不存在,那麼不會主動建立。 NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; //2-4.設定代理方法在哪個隊列中執行,如果是非主隊列,那麼代理方法將再子線程中執行 [connection setDelegateQueue:[[NSOperationQueue alloc]init]]; //2-5 建立當前線程對應的runloop,並開啟 [[NSRunLoop currentRunLoop]run]; }];}
NSURLConnection和Runloop(面試)