在网络请求之后的UI操作要放在主线程中才能刷新,否则UI不会发生变化
有两种在主线程中刷新UI的操作
1、直接在主线程中添加函数
[self performSelectorOnMainThread:@selector(download_completed:) withObject:data waitUntilDone:NO];
在download_completed:函数里面进行UI操作
2、GCD刷新主线程操作
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//在这里处理耗时间的代码块
dispatch_async(dispatch_get_main_queue(), ^{
//在这里处理UI
});
});
实例代码
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://app.tsjsr.com/rest/kaoshi/alltopic" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//耗时操作
NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
for (NSDictionary *dic in rootDic[@"list1"]) {
[_dataArray1 addObject:dic];
float Value = (float)_dataArray1.count/1073*10;
percentLabel.font = [UIFont systemFontOfSize:15];
NSLog(@"******%f",Value);
_progress.value = Value;
self.p_Value = Value;
dispatch_async(dispatch_get_main_queue(), ^{
//处理UI
[_progress setValue:Value animated:YES];
percentLabel.text = [NSString stringWithFormat:@"%.0f%%",_progress.value*100];
[_progress setNeedsLayout];
});
sleep(1);
}
NSLog(@"######%ld",_dataArray1.count);
for (NSDictionary *dic in rootDic[@"list4"]) {
[_dataArray4 addObject:dic];
}
NSLog(@"######%ld",_dataArray4.count);
[self num];
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];