我有一个UITABBAR应用程序,其中有两个视图,可以在其“ ViewWillAppear”方法中从Web加载大量数据。我想在检索此数据时显示进度栏或活动指标,以确保用户知道该应用程序没有冷冻。

我知道以前有人问过。我只需要澄清似乎是一个相反的 好的解决方案.

我在示例中施加了代码。该问题的原始Asker后来通过将数据检索放入另一个“线程”中解决了他们的问题。我理解线程的概念,但我不知道我将如何实现这一目标。

通过研究,我发现我需要将所有重型数据检索移至背景线程中,因为所有UI更新都在主线程中发生。

如果一个人如此友善以为我提供一个例子,我将非常感谢。我可以根据需要提供现有代码的一部分。

有帮助吗?

解决方案

如果使用nsurlconnection,它将自动在另一个线程上运行。

在您的ViewDidload中:

NSURLRequest *req = [NSURLRequest requestWithURL:theURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];

然后,您需要一些自定义方法。如果您输入 -connection 然后按ESC您会看到所有可以使用的不同方法。您需要三个:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // this is called when there is a response
        // if you're collecting data init your NSMutableData here
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // each time the connection downloads a 
        // packet of data it gets send here
        // so you can do [myData appendData:data];
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
        // the connection has finished so you can 
        // do what you want with the data here
}

这基本上就是所有。 Nsurlconnection处理所有多线程本身,您不必担心。现在,您可以创建一个活动指示器并显示它,因为主线程为空,它将起作用。 :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top