在OC中,子线程是否能够刷新主线程,下面可以使用代码来测试一下
@interface ViewController ()
{
UIProgressView *_progress;
CGFloat _currentLength;
BOOL is;
}
@property (nonatomic,strong) NSThread *thread;
@property (nonatomic,strong)UIImageView *image;
@property (nonatomic,strong) UILabel *label;
@end
- (void)viewDidLoad {
[super viewDidLoad];
// NSLog(@"%d",min(2, 5));
//创建一个子线程
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(increaseProgress) object:nil];
_currentLength = 0;
//创建一个进度条
_progress = [[UIProgressView alloc] initWithFrame:CGRectMake(10, 100, 300, 44)];
_progress.progress = _currentLength/TotalLength;
[self.view addSubview:_progress];
self.image = [[UIImageView alloc] initWithFrame:CGRectMake(0,230, 300, 300)];
self.image.backgroundColor = [UIColor redColor];
[self.view addSubview:self.image];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 540, 100, 20)];
self.label.backgroundColor = [UIColor orangeColor];
self.label.text = @"343";
[self.view addSubview:self.label];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, 180, 300, 44);
[button setTitle:@"start" forState:UIControlStateNormal];
button.backgroundColor = [UIColor orangeColor];
[button addTarget:self action:@selector(startIncreasementProgress) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)increaseProgress {
self.label.backgroundColor = [UIColor redColor];
self.label.text = @"555";
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 570, 300, 10)];
view.backgroundColor = [UIColor blueColor];
[self.view addSubview:view];
for (int i = 0; i < 10; i ++) {
_currentLength ++;
[NSThread sleepForTimeInterval:1.f];
//手动调用主线程,刷新UI展示
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
_progress.progress = _currentLength/TotalLength;
}
_progress.progress = 50/TotalLength;
UIImage *ima = [[UIImage alloc] init];
//在子线程中去去刷新图片
ima = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.929898.org.cn/imgall/nfwwomjvfyzwy2lbnyxgg33n/2015/f2/116/d/3.jpg"]]];
NSLog(@"222");
// }
//把图片放到主线程中去刷新
// [self performSelectorOnMainThread:@selector(updateUI:) withObject:ima waitUntilDone:NO];
[self.image setImage:ima]; }
-(void)updateUI:(UIImage *)ima{
[self.image setImage:ima];
}
- (void)updateUI { //刷新进度 _progress.progress = _currentLength/TotalLength;}
运行的结果是:点击按钮,因为进度条是开起一个子线程,在子线程中调用主线程去刷新UI,而label和图片的加载,以及uiview的显示是通过子线程去刷新UI的,你会发现,刚开始运行的时候,label和image是不变的,而进度条是一直在刷新的,而进度条是刷新的,当进度条加载完后,label会改变,UI图片会加载出来,view才会显示。而这个结果,并不是子线程可以刷新UI。在子线程中是不能进行UI 更新的,而可以更新的结果只是一个幻像:因为子线程代码执行完毕了,又自动进入到了主线程,执行了子线程中的UI更新的函数栈,这中间的时间非常的短,就让大家误以为分线程可以更新UI。如果子线程一直在运行,则子线程中的UI更新的函数栈 主线程无法获知,即无法更新 :
github