我正在尝试做这样的事情:
- (void)sectionChanged:(id)sender {
[self.view addSubview:loadingView];
// Something slow
[loadingView removeFromSuperview];
}
其中,loadView是一个带有UIActivityIndicatorView的半透明视图。但是,似乎添加的子视图更改在此方法结束之前不会生效,因此视图在变为可见之前将被删除。如果我删除removeFromSuperview语句,则视图会在缓慢处理完成后正确显示,并且永远不会被删除。有没有办法解决这个问题?
答案 0 :(得分:4)
在后台线程中运行您的慢进程:
- (void)startBackgroundTask {
[self.view addSubview:loadingView];
[NSThread detachNewThreadSelector:@selector(backgroundTask) toTarget:self withObject:nil];
}
- (void)backgroundTask {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// do the background task
[self performSelectorOnMainThread:@selector(backgroundTaskDone) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)backgroundTaskDone {
[loadingView removeFromSuperview];
}
答案 1 :(得分:1)
两个潜在的问题浮现在脑海中,两者都围绕着你如何实现“在这里做一些慢点”的代码。
首先,如果它正在锁定主线程,那么应用程序的UI可能无法及时重绘以显示视图,即添加子视图,紧密循环/密集处理占用主线程,然后立即视图已删除。
其次,如果异步进行'某事慢',则在慢速处理运行时删除视图。
有一件事是肯定的,您的要求如下:
- (void)beginProcessing {
[self.view addSubview:loadingView];
[NSThread detachNewThreadSelector:@selector(process) toTarget:self withObject:nil];
}
- (void)process {
// Do all your processing here.
[self performSelectorOnMainThread:@selector(processingComplete) withObject:nil waitUntilDone:NO];
}
- (void)processingComplete {
[loadingView removeFromSuperview];
}
- (void)beginProcessing {
[self.view addSubview:loadingView];
[NSThread detachNewThreadSelector:@selector(process) toTarget:self withObject:nil];
}
- (void)process {
// Do all your processing here.
[self performSelectorOnMainThread:@selector(processingComplete) withObject:nil waitUntilDone:NO];
}
- (void)processingComplete {
[loadingView removeFromSuperview];
}
你也可以用NSOperations达到类似的效果。