3

我为 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 的文本?

4

4 回答 4

2

问题是我发现方法'didReceiveData'将在调用连接的方法之后被调用。(方法 'didReceiveData' 将在 IBAction 'accept' 之后调用)

您希望连接connection:didReceiveData:在创建和连接之前发送给您吗?

这将导致一个问题,如果我想将标签的文本更改为接收到的字符串,代码不能写在 IBAction 'accept' 中,而必须写在方法 'didReceiveData' 中......</p>

听起来差不多。在收到之前,您无法使用收到的东西。

另一个问题是,如果我在“didReceiveData”中初始化 MainView,MainView 上的数据将被覆盖。我是否可以在不初始化 MainView 的情况下更改 labelStr 的文本?

在您的方法中创建主视图控制器和应用程序委托connection:didReceiveData:似乎真的太晚了。早点做那些事情,然后connection:didReceiveData:除了 set 什么都不做labelStr.text

顺便说一句,connection:didReceiveData:你显示泄漏的实现ReturnStr。请记住释放或自动释放您已分配的内容。

于 2009-03-16T12:33:16.423 回答
1

如果您希望您的应用程序等到数据进来,请使用 NSURLConnection 的sendSynchronousRequest:returningResponse:error:方法。但是请注意,在运行此方法时,您的应用程序的其余部分将被冻结,当然,如果用户的连接很糟糕,该方法可能需要一段时间。

于 2009-03-17T12:18:30.243 回答
0

NSURLConnection 和其他类似的类被设计为异步使用。

initWithRequest:delegate: 立即返回,并且在将委托方法发送给其委托之前,您不会对连接内容感到恼火。

于 2009-03-17T11:59:17.357 回答
0

使用 NSMutableData 而不是 NSData。

于 2010-02-22T04:02:53.847 回答