1. 创建一个线程
view plaincopy to clipboardprint?
[NSThread detachNewThreadSelect:@selector(BeginThread)
toTarget:selft
withObject:nil];
[NSThread detachNewThreadSelect:@selector(BeginThread)
toTarget:selft
withObject:nil];
2.线程里做两件,一件是后台处理耗时间的活(dosomethinglongtime),另一件是更新UI(UpdateUI)
view plaincopy to clipboardprint?
-(void) BeginThread{
[self performSelectorInBackgroud:@selector(dosomethinglongtime)
withObject:nil];
[self perfomSelectorOnMainThread:@selector(UpdateUI)
withObject:nil
watUntilDone:NO];
}
-(void) BeginThread{
[self performSelectorInBackgroud:@selector(dosomethinglongtime)
withObject:nil];
[self perfomSelectorOnMainThread:@selector(UpdateUI)
withObject:nil
watUntilDone:NO];
}
3. 那UpdateUI的数据怎么来呢?
view plaincopy to clipboardprint?
-(void)dosomethinglongtime{
// 修改共享变量 varProgress, varText等等
}
-(void)UpdateUI{
// 获得共享变量 varProgress, varText等等, 显示在界面上
}
-(void)dosomethinglongtime{
// 修改共享变量 varProgress, varText等等
}
-(void)UpdateUI{
// 获得共享变量 varProgress, varText等等, 显示在界面上
}
4.这样就完成了一个大概的流程,但是UpdateUI里不能用while(1),不然主线程会堵在UpdateUI的函数里,怎么办呢? Google了一个方法, UpdateUI的方法做了一下修改
view plaincopy to clipboardprint?
-(void)UpdateUI{
// 获得共享变量 varProgress, varText等等, 显示在界面上
if(!finished)
[NSTimer scheduledTimerWithTimeInterval:0.2
target:self
selector:@selector(UpdateUI)
userInfo:nil repeats:NO];
}
-(void)UpdateUI{
// 获得共享变量 varProgress, varText等等, 显示在界面上
if(!finished)
[NSTimer scheduledTimerWithTimeInterval:0.2
target:self
selector:@selector(UpdateUI)
userInfo:nil repeats:NO];
}
这样的意思, 如果没线程没结束,过0.2秒再回到这个函数更新界面, 如此循环, 直到结束.
以上IPhone多线程编程的一种方法, 下一篇就讲一下用NSOperation和NSOperationQueue来实现.
ios的多线程编程初体验
转载
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Qt OPC UA初体验
qtopcua源码编译、通信示例、流程分析
qtopcua OPC UA 工业自动化 -
Shell 编程初体验
经常听到 "Shell脚本"、"Shell编程"、"Bash命令",那么什么是 Shell 呢?Shell 和 Bash 有什么关系呢?我们一起来学习下吧!
后端 bash centos linux 其他 -
Fastbo-iOS 初体验
Fastbo-iOS 初体验 直接放一个官方给的中文文档吧,已经很详细了 htt
ios github 中文文档 -
初体验
刚刚申请成功,初次体验……
职场 体验 休闲