转自:http://www.devdiv.com/forum.php?mod=viewthread&tid=42809&extra=page%3D1%26filter%3Ddigest%26digest%3D1%26digest%3D1

 1. 创建一个线程


view plaincopy to clipboardprint?
[NSThread detachNewThreadSelect:@selector(BeginThread)      
  toTarget:selft      
  withObject:nil];    
[NSThread detachNewThreadSelect:@selector(BeginThread)  
  toTarget:selft  
  withObject:nil];   

2.线程里做两件,一件是后台处理耗时间的活(dosomethinglongtime),另一件是更新UI(UpdateUI)


view plaincopy to clipboardprint?
-(void) BeginThread{      
[self performSelectorInBackgroud:@selector(dosomethinglongtime)      
withObject:nil];      
[self perfomSelectorOnMainThread:@selector(UpdateUI)      
withObject:nil      
watUntilDone:NO];      
}    
-(void) BeginThread{  
[self performSelectorInBackgroud:@selector(dosomethinglongtime)  
withObject:nil];  
[self perfomSelectorOnMainThread:@selector(UpdateUI)  
withObject:nil  
watUntilDone:NO];  
}   

3. 那UpdateUI的数据怎么来呢?


view plaincopy to clipboardprint?
-(void)dosomethinglongtime{      
// 修改共享变量 varProgress, varText等等      
}      
      
-(void)UpdateUI{      
// 获得共享变量 varProgress, varText等等, 显示在界面上      
}    
-(void)dosomethinglongtime{  
// 修改共享变量 varProgress, varText等等  
}  
  
-(void)UpdateUI{  
// 获得共享变量 varProgress, varText等等, 显示在界面上  
}   

4.这样就完成了一个大概的流程,但是UpdateUI里不能用while(1),不然主线程会堵在UpdateUI的函数里,怎么办呢? Google了一个方法, UpdateUI的方法做了一下修改


view plaincopy to clipboardprint?
-(void)UpdateUI{      
// 获得共享变量 varProgress, varText等等, 显示在界面上      
if(!finished)      
     [NSTimer scheduledTimerWithTimeInterval:0.2      
target:self      
selector:@selector(UpdateUI)      
userInfo:nil repeats:NO];      
}    
-(void)UpdateUI{  
// 获得共享变量 varProgress, varText等等, 显示在界面上  
if(!finished)  
     [NSTimer scheduledTimerWithTimeInterval:0.2  
target:self  
selector:@selector(UpdateUI)  
userInfo:nil repeats:NO];  
}   

这样的意思, 如果没线程没结束,过0.2秒再回到这个函数更新界面, 如此循环, 直到结束.

以上IPhone多线程编程的一种方法, 下一篇就讲一下用NSOperation和NSOperationQueue来实现.