我为 HTTP 连接创建了一个独立的类。所有连接工作正常。问题是我发现方法'didReceiveData'将在调用连接的方法之后被调用。(方法 'didReceiveData' 将在 IBAction 'accept' 之后调用)
- (IBAction)accept:(id)sender {
[self connect:url];
//labelStr = ReturnStr; Cannot be written here.
}
-(void)connect:(NSString *)strURL
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
{
// receivedData is declared as a method instance elsewhere
receivedData = [[NSMutableData data] retain];
}
else
{
// inform the user that the download could not be made
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
[receivedData appendData:data];
ReturnStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
这将导致一个问题,如果我想将标签的文本更改为接收到的字符串,代码不能写在 IBAction 'accept' 中,而必须写在方法 'didReceiveData' 中,如下所示:
MainViewController *mainView = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
AMEAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.navController pushViewController:mainView animated:YES];
mainView.labelStr.text = ReturnStr;
另一个问题是,如果我在“didReceiveData”中初始化 MainView,MainView 上的数据将被覆盖。我是否可以在不初始化 MainView 的情况下更改 labelStr 的文本?