多线程开发之NSThread——子线程模拟耗时操作(★★★虽是转载,但是附上了个人理解,firecat推荐★★★)

364 阅读2分钟

文章来源:blog.csdn.net/m_changgong…

一、实现的功能:

a、演示多线程开发。

b、子线程中模拟耗时操作,然后通知主线程更新进度条。

关键词:多线程 NSThread 定时器

1、新建视图控制器ViewController.m(不带xib),作为根视图控制器,通过ViewController的-(void)loadView方法构建UI,ViewController.h如下:


[cpp]  view plain copy

  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewController : UIViewController{  
  4.     CGFloat progressValue; //进度条的值  
  5. }  
  6.   
  7. @property(strong,nonatomic)UIProgressView *progress;   
  8. @property(strong,nonatomic)UILabel *showValue;  
  9. @property(strong,nonatomic)UIButton *startThread;  
  10.   
  11. @end  


ViewController.m如下:


[cpp]  view plain copy

  1. #import "ViewController.h"  
  2.   
  3. @implementation ViewController  
  4. @synthesize progress;  
  5. @synthesize showValue;  
  6. @synthesize startThread;  
  7.   
  8. -(void)loadView{  
  9.     CGRect appFrame = [UIScreen mainScreen].applicationFrame;  
  10.     UIView *view = [[UIView alloc]initWithFrame:appFrame];  
  11.     self.view = view;  
  12.       
  13.     //设置背景颜色  
  14.     UIColor *bgcolor = [UIColor grayColor];  
  15.     [self.view setBackgroundColor:bgcolor];  
  16.       
  17.     [self initViews];  
  18. }  
  19.   
  20. //初始化视图组件  
  21. -(void)initViews{  
  22.     //初始化progress  
  23.     CGRect frame = CGRectMake(50, 50, 200, 30);  
  24.     progress = [[UIProgressView alloc]initWithFrame:frame];  
  25.     [self.view addSubview:progress];  
  26.       
  27.     //初始化showValue  
  28.     showValue = [[UILabel alloc]init];  
  29.     frame = showValue.frame;  
  30.     frame.origin.x = CGRectGetMaxX(progress.frame)+10;  
  31.     frame.origin.y = CGRectGetMinY(progress.frame);  
  32.     frame.size.width = 35;  
  33.     frame.size.height = 15;  
  34.     showValue.frame = frame;  
  35.     showValue.backgroundColor = [UIColor redColor];  
  36.     showValue.text = @"0.0";  
  37.     [self.view addSubview:showValue];  
  38.       
  39.     //初始化startThread  
  40.     startThread = [[UIButton alloc]init];  
  41.     frame = startThread.frame;  
  42.     frame.origin.x = 110;  
  43.     frame.origin.y = 80;  
  44.     frame.size.width = 100;  
  45.     frame.size.height = 50;  
  46.     startThread.frame = frame;  
  47.     UIImage *img = [UIImage imageNamed:@"btn.png"];  
  48.     [startThread setBackgroundImage:img forState:UIControlStateNormal];  
  49.     [startThread setTitleColor:[UIColor colorWithRed:1.0 green:0 blue:0 alpha:1.0] forState:UIControlStateNormal];  
  50.     [startThread setTitle:@"开启子线程" forState:UIControlStateNormal];  
  51.     //设置事件  
  52.     [startThread addTarget:self action:@selector(startThreadButtonPressed) forControlEvents:UIControlEventTouchUpInside];  
  53.     [self.view addSubview:startThread];  
  54. }  
  55.   
  56. //开启子线程  
  57. -(void)startThreadButtonPressed{  
  58.     progress.progress = 0.0;  
  59.     showValue.text = @"0.0";  
  60.     startThread.hidden = YES;  
  61.     //该语句会让主线程堵塞2秒,这就是为什么要将耗时操作放在子线程的原因之一  
  62.     //[NSThread sleepForTimeInterval:2];  
  63.       
  64.     //开启一个新线程  
  65.     [NSThread detachNewThreadSelector:@selector(doJobInBackground) toTarget:self withObject:nil];  
  66. }  
  67.   
  68. //子线程,后台执行工作  
  69. -(void)doJobInBackground{  
  70.     //睡眠,模拟子线程中耗时操作  
  71.     [NSThread sleepForTimeInterval:2];  
  72.     //通知主线程执行更新操作  
  73.     [self performSelectorOnMainThread:@selector(invalidateProgress) withObject:nil waitUntilDone:NO];  
  74. }  
  75.   
  76. //更新进度  
  77. -(void)invalidateProgress{  
  78.     progressValue = [progress progress];  
  79.     showValue.text = [NSString stringWithFormat:@"%.2f",progressValue];  
  80.     if(progressValue < 1.0){  
  81.         progress.progress = progressValue+0.02;  
  82.         //启动定时器  
  83.         [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(invalidateProgress) userInfo:nil repeats:NO];  
  84.     }else{  
  85.         progress.progress = 1.0;  
  86.         showValue.text = @"1.0";  
  87.         startThread.hidden = NO;  
  88.     }  
  89. }  
  90.   
  91. - (void)viewDidUnload  
  92. {  
  93.     [super viewDidUnload];  
  94.     // Release any retained subviews of the main view.  
  95.     progress = nil;  
  96.     showValue = nil;  
  97.     startThread = nil;  
  98. }  
  99.   
  100. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  101. {  
  102.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  103. }  
  104.   
  105. @end  


2、运行效果如下:

************

\

二、firecat个人实践

a、添加了函数参数的传递。

b、子线程while循环,一边延时,主线程进度条一边走动。

//

//  ViewController.m

//  iphone1

//

//  Created by firecat on 15-4-12.

//  Copyright (c) 2015年 INVT. All rights reserved.

//

\

#import "ViewController.h"

\

@interface ViewController () {

  bool bStart;

}

- (IBAction)mybtnStart:(id)sender;

- (IBAction)mybtnEnd:(id)sender;

@property(weak, nonatomic) IBOutlet UILabel *mylabel;

@property(weak, nonatomic) IBOutlet UIProgressView *myprogress;

\

@end

\

@implementation ViewController

\

- (void)viewDidLoad {

  [super viewDidLoad];

  // Do any additional setup after loading the view, typically from a nib.

}

\

- (void)didReceiveMemoryWarning {

  [super didReceiveMemoryWarning];

  // Dispose of any resources that can be recreated.

}

\

- (IBAction)mybtnStart:(id)sender {

  self.myprogress.progress = 0;

  self.mylabel.text = @"0.00";

\

  //开启一个新线程

  [NSThread detachNewThreadSelector:@selector(doJobInBackground)

                           toTarget:self

                         withObject:nil];

  bStart = YES;

}

\

//子线程,后台执行工作

- (void)doJobInBackground {

  float f = 0.0;

  NSNumber *var = [NSNumber numberWithFloat:f];

\

  while (1) {

\

    if (!bStart) {

      return;

    }

\

    f += 0.1;

    var = [NSNumber numberWithFloat:f];

\

    //通知主线程执行更新操作

    [self performSelectorOnMainThread:@selector(invalidateProgress:)

                           withObject:var //传递参数,必须是obj类型

                        waitUntilDone:NO];

\

    //睡眠,模拟子线程中耗时操作

    [NSThread sleepForTimeInterval:0.5];

\

    if (f >= 1) {

      return;

    }

  }

}

\

//更新进度

- (void)invalidateProgress:(NSNumber *)var {

  self.myprogress.progress = var.floatValue;

  self.mylabel.text = [NSString stringWithFormat:@"%.2f", var.floatValue];

}

\

- (IBAction)mybtnEnd:(id)sender {

  bStart = NO;

}

@end

\