我有一个带有方法(getAndPlaySong)的类,它从服务器获取文本文件,从文本中获取特定字符串,并使用字符串(URL)从服务器获取音乐文件。获取文本文件的第一个服务器调用很快,所以我同步实现了它。第二个需要更长的时间,我想在它发生时更新显示。
我希望该方法在继续之前等待异步请求完成。我尝试在 connectionDidFinishLoading 方法中放置一个 BOOL:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[_receivedData length]);
[AppDelegate playAudioWithData: _receivedData];
_dataIsReceived = YES; //BOOL
// release the connection, and the data object
[connection release];
[_receivedData release];
}
然后在 getAndPlaySong 方法中放置一个 while 循环:
[self startRequest: correctSongURL]; starts the request asynchronously
while (!_dataIsReceived) {
//do stuff
}
结果是应用程序在到达循环时挂起。循环永远不会终止,我永远不会得到“Succeeded ...”输出。我有点困惑,将不胜感激一些意见。