2010-05-04 54 views
0

我试图做这样的事情:视图叠加添加到iPhone应用程序

- (void)sectionChanged:(id)sender { 
    [self.view addSubview:loadingView]; 
    // Something slow 
    [loadingView removeFromSuperview]; 
} 

其中loadingView是一个UIActivityIndi​​catorView半透明视图。但是,似乎添加的子视图更改直到此方法结束才会生效,因此在视图变为可见之前将其删除。如果我删除removeFromSuperview语句,那么在缓慢的处理完成之后视图会正常显示,并且永远不会被删除。有什么办法可以解决这个问题吗?

回答

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]; 
} 
+0

非常好,谢谢。 dannywartnaby的答案几乎完全相同,但我让你记住一个自动释放池。 – 2010-05-04 21:56:34

1

两个潜在的问题映入脑海,围绕你是如何实现“在这里做一些慢”的代码都居中。

首先,如果它锁定了主线程,那么应用程序的UI可能不会被重绘以及时显示视图,即添加子视图,紧密循环/密集处理捆绑主线程,然后立即该视图被删除。其次,如果'异步缓慢'是异步完成的,则视图在缓慢处理运行时被删除。

肯定

一个东西,你的要求如下:

  1. 添加一个子视图来显示某种“装载”鉴于
  2. 调用运行速度慢一块的功能
  3. 一旦慢跑功能完成,删除'加载'子视图。

- (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类似的东西。

相关问题