Article source: blog.csdn.net/m_changgong…

I. Functions achieved:

A, demonstrate multithreaded development.

B. Simulate time-consuming operations in child threads and notify the main thread to update the progress bar.

Key words: multithreading NSThread timer

Create ViewController viewcontroller. m (without xib) as the root ViewController, build UI from ViewController -(void)loadView method, viewcontroller. h as follows:


[cpp]  view plain copy

  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewController : UIViewController{  
  4. CGFloat progressValue; // Progress bar value
  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 is as follows:


[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. // Set the background color
  14.     UIColor *bgcolor = [UIColor grayColor];  
  15.     [self.view setBackgroundColor:bgcolor];  
  16.       
  17.     [self initViews];  
  18. }  
  19.   
  20. // Initialize the view component
  21. -(void)initViews{  
  22. // Initialize progress
  23.     CGRect frame = CGRectMake(50, 50, 200, 30);  
  24.     progress = [[UIProgressView alloc]initWithFrame:frame];  
  25.     [self.view addSubview:progress];  
  26.       
  27. // Initialize 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. // Initialize 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: blue 0:0 alpha: 1.0] forState: UIControlStateNormal];
  50. [startThread setTitle: @ “open the child thread” forState: UIControlStateNormal];
  51. // Set the event
  52.     [startThread addTarget:self action:@selector(startThreadButtonPressed) forControlEvents:UIControlEventTouchUpInside];  
  53.     [self.view addSubview:startThread];  
  54. }  
  55.   
  56. // Start the child thread
  57. -(void)startThreadButtonPressed{  
  58. Progress. Progress = 0.0;
  59. ShowValue. Text = @ “0.0”;
  60.     startThread.hidden = YES;  
  61. // This statement blocks the main thread for 2 seconds. Is that one of the reasons for putting time-consuming operations on child threads
  62.     //[NSThread sleepForTimeInterval:2];  
  63.       
  64. // Start a new thread
  65.     [NSThread detachNewThreadSelector:@selector(doJobInBackground) toTarget:self withObject:nil];  
  66. }  
  67.   
  68. // The child thread performs the work in the background
  69. -(void)doJobInBackground{  
  70. // Sleep, simulating time-consuming operations in child threads
  71.     [NSThread sleepForTimeInterval:2];  
  72. // Notify the main thread to perform the update operation
  73.     [self performSelectorOnMainThread:@selector(invalidateProgress) withObject:nil waitUntilDone:NO];  
  74. }  
  75.   
  76. // Update progress
  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. // Start timer
  83. [NSTimer scheduledTimerWithTimeInterval: 0.2 target: self selector: @ the selector (invalidateProgress) the 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. The operation effect is as follows:

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

\

Second, firecat personal practice

A, added function parameter passing.

B, the child thread while loop, while the delay, the main thread progress bar walking.

//

//  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. Where. Text = @ “0.00”;

\

// Start a new thread

  [NSThread detachNewThreadSelector:@selector(doJobInBackground)

                           toTarget:self

                         withObject:nil];

  bStart = YES;

}

\

// The child thread performs the work in the background

– (void)doJobInBackground {

Float f = 0.0;

  NSNumber *var = [NSNumber numberWithFloat:f];

\

  while (1) {

\

if (! bStart) {

      return;

    }

\

F + = 0.1;

    var = [NSNumber numberWithFloat:f];

\

// Notify the main thread to perform the update operation

    [self performSelectorOnMainThread:@selector(invalidateProgress:)

WithObject :var // pass parameters, which must be of type obj

                        waitUntilDone:NO];

\

// Sleep, simulating time-consuming operations in child threads

[NSThread sleepForTimeInterval: 0.5];

\

    if (f >= 1) {

      return;

    }

  }

}

\

// Update progress

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

  self.myprogress.progress = var.floatValue;

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

}

\

– (IBAction)mybtnEnd:(id)sender {

  bStart = NO;

}

@end

\