当你使用NSURLConnection异步模式时,比如代码如下:
NSString *url = [NSString stringWithFormat:@"http://google.cn/...",...];
url = [urlstringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
connection= [[NSURLConnection alloc] initWithRequest:requestdelegate:self];
并实现了NSURLConnection的代理方法:
#pragma mark NSURLConnection delegate methods
// The following are delegate methods for NSURLConnection.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
但是你发现代码方法永远执行不到。
原因一般是因为这些方法是在一个单独线程中执行,需要一段时间来处理网络数据。
而在此之前你可能在别处退出了该线程。
为了避免这种情况,通常你可以在发送URL请求后,等待数据处理完成再做下一步的事情,这样就可以和主线程或其它线程同步:
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
finished = TRUE;
}