主线程和后台线程的通信
本篇要达到的效果就是:一边执行for循环 ,一边界面能实时查看进度条
-(void)viewDidLoad添加代码段
//新建label
self.myProcessView=[[UIProgressView alloc]init];
self.myProcessView.frame=CGRectMake(20, 20, 280, 10);
[self.view addSubview:self.myProcessView];
//进度条
-(void)updateProgressViewWithPercentage:(NSNumber*)percentageDone{
[self.myProcessView setProgress:[percentageDone floatValue] animated:YES];
}
-(void)bigTask{
@autoreleasepool {
int updateUIWhen = 1000;
for (int i=0; i<10000; i++) {
NSString*newString=[NSString stringWithFormat:@"i=%d",i];
NSLog(@"%@ ",newString);
if (i==updateUIWhen) {
float f=(float)i/10000;
NSNumber*percentDone=[NSNumber numberWithFloat:f];
[self performSelectorOnMainThread:@selector(updateProgressViewWithPercentage:)withObject:percentDone waitUntilDone:YES];
updateUIWhen=updateUIWhen+1000;
}
}
[self performSelectorOnMainThread:@selector(updateProgressViewWithPercentage:)withObject:[NSNumber numberWithFloat:1.0] waitUntilDone:YES];
[self.myActivityIndicator stopAnimating];
}
}
更新界面根据updateUIWhen 这个整数 通过判断所占总共进度的多少 达到实时10% 就会更新界面
performSelectorOnMainThread: WithObject: waitUntilDone: 是主线程和后台线程通信的根本