线程中如何更新对话框中的数据

iOS 码拜 9年前 (2015-04-30) 742次浏览 0个评论

我开启一个线程,用来做一些耗时的操作,同时show一个UIAlertView。想再线程中更新UIAlertView的Message,比如说

“正在同步数据xx%”

这代码要怎么写?新手请教,谢谢!

线程中如何更新对话框中的数据
100分
抛砖引玉

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"进度" message:@"1%" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
[alert show];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    alert.message = @"10%";
});
线程中如何更新对话框中的数据
引用 1 楼 zhangao0086 的回复:

抛砖引玉

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"进度" message:@"1%" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
[alert show];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    alert.message = @"10%";
});

非常感谢,已经搞定

线程中如何更新对话框中的数据
使用GCD处理多线程编程还是非常方便的。GCD用非常简洁的方法,实现了极为复杂的多线程编程。使用它我们可以很简单的创建一个异步操作

dispatch_async(queue, ^{
         /*
          *处理比较耗时的操作
          */

           //////与主线程通讯
          dispatch_async(dispatch_get_main_queue(), ^{
                  //////只在主线程中可以执行的处理,如UI的更新
         });
});

如果使用上面范式来处理你的问题的话,像这样

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"进度" message:@"1%" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
[alert show];
dispatch_async(dispatch_get_global_queue(0,0), ^{
         sleep(2); /////阻塞线程,模拟耗时操作
          dispatch_async(dispatch_get_main_queue(), ^{
                  alert.message = @"正在同步数据20%"
         });
});

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明线程中如何更新对话框中的数据
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!