NSURLConnection代理方法默认在主线程执行
让代理方法在子线程执行的方法 1.给代理方法开子线程(若方法多 开子线程越多 不建议使用)2. 统一开线程
统一开线程
- (void)delegate
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"]];
//connectionWithRequest该方法内部会将connetion对象作为一个source添加到当前runloop 指定运行模式为默认
//所以该代码块结束时 connetion并没有被销毁
//[NSURLConnection connectionWithRequest:request delegate:self];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection start];
//设置代理方法在子线程中调用方法 1.在代理方法中开启子线程 2.统一设置
[connection setDelegateQueue:[[NSOperationQueue alloc]init]];
NSLog(@"-----------------");
}
#pragma mark ----Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse-------%@",[NSThread currentThread]);
}
把网络请求放在子线程中
1.connectionWithRequest
- (void)delegate2
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"]];
//connectionWithRequest该方法内部会将connetion对象作为一个source添加到当前runloop 指定运行模式为默认
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//因为子线程没有开启runloop
//添加runloop 并开启
[[NSRunLoop currentRunLoop] run];
NSLog(@"-----%@",[NSThread currentThread]);
});
}
2.initWithRequest:request delegate
- (void)delegate3
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
//设置代理方法在子线程中调用方法 1.在代理方法中开启子线程 2.统一设置
[connection setDelegateQueue:[[NSOperationQueue alloc]init]];
//start若果connection没有添加到runloop中,那么该方法内部会自动添加到runloop ,若当前runloop没有开启,那么该方法内部会自动获得当前线程对应的runloop并开启
[connection start];
NSLog(@"-----------------");
});
}