iOS开发,在main thread以外的thread更新UI
2024-10-21 13:24:45
如果需要在异步任务(Async Task)中更新UI,若直接设置UI,会导致程序崩溃。
例如,在异步block中去更改UI:
NSOperationQueue *queue=[[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
@autoreleasepool {
// the other codes ...
_textView.text = [_textView.text stringByAppendingString:stringResult];
}
}];
运行时会崩溃,并报错,意思是此操作只能在主线程执行:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'
正确的方法是通过mainQueue向主线程队列添加block来执行更新UI,如下:
NSOperationQueue *queue=[[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
@autoreleasepool {
// the other codes ...
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// update UI here
_textView.text = [_textView.text stringByAppendingString:stringResult];
}];
}
}];
最新文章
- FILE文件流的中fopen、fread、fseek、fclose的使用
- node.js下使用RSA加密事例(windows)
- 【BZOJ-1419】Red is good 概率期望DP
- loadrunner实现excel文件导出操作
- Birt使用总结
- zh-Hans vs.net 通过 管理nuget程序包下载简体中文语言包 zh-cn
- jQuery 参考手册 - 遍历
- WEB- 冻结TABLE的头和列
- C# WinForm捕获未处理的异常
- HDU 5968 异或密码 【模拟】 2016年中国大学生程序设计竞赛(合肥)
- sid超过8个字符处理步骤
- js中widow.open()方法详解
- C++它 typedef void *HANDLE
- HTML5中将video设置为背景的方法
- UITextField总结
- [刷题]Codeforces 786A - Berzerk
- Java面向对象-方法的值传递和引用传递
- Linux系统下常用命令
- noode inquirer
- BIOS备忘录之IIC(touchpad)设备
热门文章
- python_unittest详解
- jquery详解图片平滑滚动
- JQUERY获取html标签自定义属性值或data值
- POJ 1504,ZOJ 2001,UVA 713, Adding Reversed Numbers,错误,已找到错误
- 从信用卡欺诈模型看不平衡数据分类(1)数据层面:使用过采样是主流,过采样通常使用smote,或者少数使用数据复制。过采样后模型选择RF、xgboost、神经网络能够取得非常不错的效果。(2)模型层面:使用模型集成,样本不做处理,将各个模型进行特征选择、参数调优后进行集成,通常也能够取得不错的结果。(3)其他方法:偶尔可以使用异常检测技术,IF为主
- 常用的Hql语句(转)
- html网页小图标
- rabbitmq-交换机
- stl_vector.h
- 设置Suse linux 用户远程登录超时时间