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 のテキストを変更することはできますか?