ASIHTTPRequest占用主线程问题解决

来源:互联网 发布:优化顶碗少年阅读答案 编辑:程序博客网 时间:2024/06/09 16:49
ASIHTTPRequest是个很易用的iOS / Mac OS X平台的HTTP库,不过当下载线程数超过2个时,就会影响到主线程响应用户请求的速度了。经测试发现completionBlock总是在主线程调用,而NSOperation的文档中却说一般会在子线程中执行。
于是看了下ASIHTTPRequest.m,终于发现问题所在了:
// Subclasses might override this method to process the result in the same thread// If you do this, don't forget to call [super requestFinished] to let the queue / delegate know we're done- (void)requestFinished{#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING    NSLog(@"[STATUS] Request finished: %@",self);#endif    if ([self error] || [self mainRequest]) {        return;    }    if ([self isPACFileRequest]) {        [self reportFinished];    } else {        [self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];    }}
这段代码显示了,在不使用自动代理脚本时,就会在主线程执行reportFinished。

解决的办法很简单,可以按它所说的继承ASIHTTPRequest,并改写requestFinished方法。或者像我这种懒人,直接改源码:
- (void)requestFinished{#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING    NSLog(@"[STATUS] Request finished: %@",self);#endif    if ([self error] || [self mainRequest]) {        return;    }    [self reportFinished];}

改完后重新构建一遍,发现至少5个下载线程时也不会影响主线程了,搞定收工~ 
原创粉丝点击