NSURLConnection代理方法线程问题

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(@"-----------------");

    });

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值