Ash*_*shu 7 iphone grand-central-dispatch ios objective-c-blocks
我GCD用来HTTP异步发送请求.这是不起作用的代码:
dispatch_async(connectionQueue, ^{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];//Not working
});
Run Code Online (Sandbox Code Playgroud)
上面的代码根本不起作用.我没有在NSURLConnectionDelegate的方法中收到任何回调.
但是,当我尝试以下代码时,一切正常,我得到了适当的回调
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
dispatch_async(connectionQueue, ^{
[connection start]; // working fine. But WHY ????
});
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下块/ GCD的奇怪行为吗?
在代码示例的第一部分尝试这个 -
dispatch_async(dispatch_get_main_queue(), ^(void){
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
Run Code Online (Sandbox Code Playgroud)
如果您将连接放入后台队列,则在队列完成后它会被推走,因此您不会收到委托回调。连接可以位于主队列中,因此它保留在主运行循环中以便发生回调。或者,您可以创建自己的运行循环,按照其他人的建议为您处理后台操作。
| 归档时间: |
|
| 查看次数: |
2838 次 |
| 最近记录: |