`
janedoneway
  • 浏览: 569689 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

iPhone多线程编程初体验

 
阅读更多

From: http://mobile.51cto.com/iphone-267455.htm

 

找了很长时间IPhone下多线程的编程的内容, 用到的类是UIKit的中NSThread.。

 

在google过程中,发现很多文都惊喜地标题着类似< 多线程的iOS4来了>, 这些想正向引导一下, iOS4的亮点在于多任务,一个任务为一个进程,也叫多进程, 而多线程在早期的IPHONEOS上都是有的.

 

IPHONE OS中任务的概念是一个应用, 在一个时间你只能做一件事情, 即不能同时玩游戏,同时上QQ. 而多任务的时候是可以这么做的.

 

流程大概如下:

 

1. 创建一个线程

  1. [NSThread detachNewThreadSelect:@selector(BeginThread)
  2. toTarget:selft
  3. withObject:nil];

 

2.线程里做两件,一件是后台处理耗时间的活(dosomethinglongtime),另一件是更新UI(UpdateUI)

  1. view plaincopy to clipboardprint?
  2. (void) BeginThread{
  3. [self performSelectorInBackgroud:@selector(dosomethinglongtime)
  4. withObject:nil];
  5. [self perfomSelectorOnMainThread:@selector(UpdateUI)
  6. withObject:nil
  7. watUntilDone:NO];
  8. }

 

3. 那UpdateUI的数据怎么来呢

  1. view plaincopy to clipboardprint?
  2. -(void)dosomethinglongtime{
  3. // 修改共享变量 varProgress, varText等等
  4. }
  5. {void)UpdateUI{
  6. // 获得共享变量 varProgress, varText等等, 显示在界面上
  7. }

 

这样就完成了一个大概的流程,但是UpdateUI里不能用while(1),不然主线程会堵在UpdateUI的函数里,怎么办呢? Google了一个方法, UpdateUI的方法做了一下修改

 

这样的意思, 如果没线程没结束,过0.2秒再回到这个函数更新界面, 如此循环, 直到结束.

  1. view plaincopy to clipboardprint?
  2. (void)UpdateUI{
  3. // 获得共享变量 varProgress, varText等等, 显示在界面上
  4. if(!finished)
  5. [NSTimer scheduledTimerWithTimeInterval:0.2 target:self
  6. selector:@selector(UpdateUI) userInfo:nil repeats:NO];
  7. }

 

以上IPhone多线程编程的一种方法, 当然还有人提议用NSOperation和NSOperationQueue,但我试了一把,没把效果试出来, 等有结果再回来更新. 嘿嘿.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics