我有一个这样的案例:我的应用程序需要将图像上传到服务器,我想向用户显示上传状态。例如,我选择了4张图片,当app上传图片1时,hud文本标签应该在上传图片2时显示“上传图片1/4”,显示“上传图片2/4”等,我不想将上传过程放在后台,所以假设上传过程在主线程中执行。因此,在上传图片时,主线程会被阻塞。所以hud的事情不会立即起作用。如何解决这个问题,有人能帮上忙吗?我的代码是这样的:
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
hud.labelText = self.maskTitle;//change hud lable text
[self uploadImage:i];//upload image, this would take long, will block main thread
}发布于 2013-01-02 21:56:38
你永远不应该在主线程上执行繁重的操作,但是如果你真的想这样做,你可以这样做
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
hud.labelText = self.maskTitle;//change hud lable text
[self performSelector:@selector(uploadImage:) withObject:@i afterDelay:0.001];
}插入延迟将允许NSRunLoop在您开始上载图像之前完成其周期,以便更新UI。这是因为UIKit在NSRunLoop的当前迭代结束时绘制。
另一种方法是手动运行NSRunLoop,例如
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
hud.labelText = self.maskTitle;//change hud lable text
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
[self performSelector:@selector(uploadImage:) withObject:@i afterDelay:0];
}请注意,在这两个示例中,您的uploadImage:方法现在都需要接受NSNumber而不是int。
https://stackoverflow.com/questions/14123108
复制相似问题