我想首先显示视图,然后在后台线程中加载数据。当我从根控制器导航到视图控制器时,我想先显示视图。截至目前,它一直停留在根控制器上,直到加载视图控制器。这是我的根控制器代码。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ProductDetailViewController *tempProductDetail = [[ProductDetailViewController alloc] init];
[self.navigationController pushViewController:tempProductDetail animated:YES];
[tempProductDetail release];
}
ProductDetailViewController,这里我想首先显示视图,然后加载数据......
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[self performSelectorOnMainThread:@selector(workerThread) withObject:nil waitUntilDone:NO];
}
-(void) workerThread{
NSAutoreleasePool *arPool = [[NSAutoreleasePool alloc] init];
[arPool release];
}
不知道我做错了什么。请帮忙。
答案 0 :(得分:3)
使用[self performSelectorInBackground:@selector(workerThread) withObject:nil];
代替
[self performSelectorOnMainThread:@selector(workerThread) withObject:nil waitUntilDone:NO];
答案 1 :(得分:1)
找到了这个问题的答案,
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[self performSelectorInBackground:@selector(workerThread) withObject:nil];
}
- (void) workerThread
{
// Set up a pool for the background task.
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// only do data fetching here, in my case from a webservice.
//...
// Always update the components back on the main UI thread.
[self performSelectorOnMainThread:@selector(displayView) withObject:nil waitUntilDone:YES];
[pool release];
}
// Called once the background thread task has finished.
- (void) displayView
{
//here in this method load all the UI components
}
答案 2 :(得分:0)
考虑使用以下模式代替线程,在我看来它更清晰:
- (void)viewWillAppear:(BOOL)animated
{
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(someFunction)
object:nil];
[[NSOperationQueue currentQueue] addObject:operation]; // this will actually start the thread
[operation release];
}
- (void)someFunction
{
// don't need to initialize and release an autorelease pool here,
// you can just write a function as usual ...
[self updateUI];
}
- (void)updateUI
{
if (![NSThread isMainThread]) // if we need a UI update, force it on main thread
{
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
return;
}
// do UI updates here
}
通过以这种方式编写代码,您可以更加动态地决定要线程化的函数,因为没有自动释放池要求。如果您需要进行UI更新, updateUI 函数将确保它自己在主线程上运行,因此调用者不需要考虑这一点。