0

我正在尝试异步加载网页内容。一旦调用了 connectionDidFinishLoading 方法,我不确定如何更新视图控制器中的标签/其他内容。在下面的示例中,我只是尝试更新标签以显示内容已加载。我该怎么做?谢谢!

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[responseData
                                                   length]);
    NSString *txt = [[NSString alloc] initWithData:responseData encoding: 
    NSASCIIStringEncoding];

    label.text = @"DISPLAY THIS WHEN FINISHED";  
}

有人告诉我让我的 viewController 成为 NSURLConnectionDelegate,然后从 viewDidLoad 运行 fetchData 方法,然后使用在 connectionDidFinishLoading 中获取数据时为我们获取数据的数据。有谁知道从哪里开始?谢谢!

4

1 回答 1

1

正如 Ramy 正确指出的那样,您必须在主线程上更新您的 UI,然后:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   NSLog(@"Succeeded! Received %d bytes of data",[responseData length]);
   NSString *txt = [[NSString alloc] initWithData:responseData 
                                         encoding: NSASCIIStringEncoding];

  NSString *text = @"DISPLAY THIS WHEN FINISHED";
  [label performSelectorOnMainThread:@selector(setText:) withObject:text waitUntilDone:NO]
}
于 2013-02-23T10:46:15.457 回答