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
- #import <UIKit/UIKit.h>
- @interface ViewController : UIViewController{
- CGFloat progressValue; // Progress bar value
- }
- @property(strong,nonatomic)UIProgressView *progress;
- @property(strong,nonatomic)UILabel *showValue;
- @property(strong,nonatomic)UIButton *startThread;
- @end
ViewController. M is as follows:
[cpp] view plain copy
- #import “ViewController.h”
- @implementation ViewController
- @synthesize progress;
- @synthesize showValue;
- @synthesize startThread;
- -(void)loadView{
- CGRect appFrame = [UIScreen mainScreen].applicationFrame;
- UIView *view = [[UIView alloc]initWithFrame:appFrame];
- self.view = view;
- // Set the background color
- UIColor *bgcolor = [UIColor grayColor];
- [self.view setBackgroundColor:bgcolor];
- [self initViews];
- }
- // Initialize the view component
- -(void)initViews{
- // Initialize progress
- CGRect frame = CGRectMake(50, 50, 200, 30);
- progress = [[UIProgressView alloc]initWithFrame:frame];
- [self.view addSubview:progress];
- // Initialize showValue
- showValue = [[UILabel alloc]init];
- frame = showValue.frame;
- frame.origin.x = CGRectGetMaxX(progress.frame)+10;
- frame.origin.y = CGRectGetMinY(progress.frame);
- frame.size.width = 35;
- frame.size.height = 15;
- showValue.frame = frame;
- showValue.backgroundColor = [UIColor redColor];
- ShowValue. Text = @ “0.0”;
- [self.view addSubview:showValue];
- // Initialize startThread
- startThread = [[UIButton alloc]init];
- frame = startThread.frame;
- frame.origin.x = 110;
- frame.origin.y = 80;
- frame.size.width = 100;
- frame.size.height = 50;
- startThread.frame = frame;
- UIImage *img = [UIImage imageNamed:@”btn.png”];
- [startThread setBackgroundImage:img forState:UIControlStateNormal];
- [startThread setTitleColor: [UIColor colorWithRed: 1.0 green: blue 0:0 alpha: 1.0] forState: UIControlStateNormal];
- [startThread setTitle: @ “open the child thread” forState: UIControlStateNormal];
- // Set the event
- [startThread addTarget:self action:@selector(startThreadButtonPressed) forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:startThread];
- }
- // Start the child thread
- -(void)startThreadButtonPressed{
- Progress. Progress = 0.0;
- ShowValue. Text = @ “0.0”;
- startThread.hidden = YES;
- // This statement blocks the main thread for 2 seconds. Is that one of the reasons for putting time-consuming operations on child threads
- //[NSThread sleepForTimeInterval:2];
- // Start a new thread
- [NSThread detachNewThreadSelector:@selector(doJobInBackground) toTarget:self withObject:nil];
- }
- // The child thread performs the work in the background
- -(void)doJobInBackground{
- // Sleep, simulating time-consuming operations in child threads
- [NSThread sleepForTimeInterval:2];
- // Notify the main thread to perform the update operation
- [self performSelectorOnMainThread:@selector(invalidateProgress) withObject:nil waitUntilDone:NO];
- }
- // Update progress
- -(void)invalidateProgress{
- progressValue = [progress progress];
- showValue.text = [NSString stringWithFormat:@”%.2f”,progressValue];
- If (progressValue < 1.0) {
- Progress. Progress = progressValue + 0.02;
- // Start timer
- [NSTimer scheduledTimerWithTimeInterval: 0.2 target: self selector: @ the selector (invalidateProgress) the userInfo: nil repeats: NO];
- }else{
- Progress. Progress = 1.0;
- ShowValue. Text = @ “1.0”;
- startThread.hidden = NO;
- }
- }
- – (void)viewDidUnload
- {
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- progress = nil;
- showValue = nil;
- startThread = nil;
- }
- – (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- return (interfaceOrientation ! = UIInterfaceOrientationPortraitUpsideDown);
- }
- @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
\