您好我需要显示活动指示但无法找到正确的方法,我尝试的是:
1)在ViewDidLod
中 [self performSelectorOnMainThread:@selector(setupActivityIndicator) withObject:nil waitUntilDone:NO];
[self userDataFromServer]
;
[self performSelectorOnMainThread:@selector(stopActivityIndicatorInMainThread) withObject:nil waitUntilDone:NO]
---- ----- OR
2)在ViewDidLod
中 [self startActivityIndicator];
[self userDataFromServer]
;
[self stopActivityIndicator];
两者都是以不合适的方式工作。任何人都可以帮助我如何在并行线程上使用activityindicator。
答案 0 :(得分:1)
没有必要在viewDidLoad中调用performSelectorOnMainThread:因为你很可能已经在主线程上了。 UIAit是UIActivityIndicator的一部分,总是需要从主线程中调用。
我认为您可能想要做的是在辅助线程上运行userDataFromServer。在viewDidLoad中尝试
[self performSelectorInBackground:@selector(userDataFromServer) withObject:nil];
然后在userDataFromServer方法中,确保包含NSAutoreleasePool
-(void)userDataFromServer {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//code to actually get the data
[pool release];
}
答案 1 :(得分:1)
根据我的经验,从服务器下载数据的最佳做法是
- (void)viewDidLoad {
[self startActivityIndicator];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:aRequest]] delegate:self];
[conn release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Store your data
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"ERROR DOWNLOADING");
// Here you can display an UIAlert message
// Then stop your activity indicator
[self stopActivityIndicator];
// Release the connection now that it's finished
connection = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"FINISH DOWNLOAD");
// Or just stop
[self stopActivityIndicator];
// Do something
// Release the connection now that it's finished
connection = nil;
}
答案 2 :(得分:0)
活动指标只显示有活动。
例如,如果您使用NSURLConnection在单独的线程上运行NSURLRequest,您可以将活动指示符添加到viewDidLoad
上的视图,然后在执行[activityIndicator startAnimating]
时执行[urlConnection start]
。然后,当你到达-connectionDidFinish
时,你可以阻止它。如果你明白。
我假设你的问题是你在userDataFromServer
做了一些“悬挂”iphone的事情,所以最好在另一个线程上执行THAT选择器。你可以发布这种方法吗?如果您正在使用NSURLRequest,那么如果您添加[NSURLConnection connectionWithRequest:myRequest]
并查找NSURLConnection
委托方法,那么这将为您异步工作。