Cocoa Touch - 在加载UITabBar视图时显示活动指示器

时间:2010-12-21 09:27:32

标签: iphone multithreading cocoa-touch uitabbar nsnotificationcenter

我有一个带有两个视图的UITabBar应用程序,它们在“viewWillAppear”方法中从Web加载大量数据。我想在检索此数据时显示进度条或活动指示器,以确保用户知道应用程序未被冻结。

我知道以前曾经问过这个问题。我只需要对似乎是good solution的内容进行一些澄清。

我已经对示例中的代码表示赞赏。问题的原始提问者后来通过将数据检索放入另一个“线程”来解决他们的问题。我理解线程的概念,但我不知道我会如何暗示这一点。

通过研究,我发现我需要将所有重度数据检索移动到后台线程中,因为所有UI更新都发生在主线程中。

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

1 个答案:

答案 0 :(得分:3)

如果使用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处理所有多线程本身,您不必担心。现在您可以创建一个活动指示器并显示它,它将起作用,因为主线程是空的。 :)