iOS学习笔记---利用NSThread实现异步更新UI和下载图片

ios的NSThread和android的Thread的差不多,都是开启一个线程,因为子线程中是不能进行UI更新操作的,所以子线程需要与主线程进行沟通。一般情况下android的Thread都会结合handler共同实现UI的更新,而ios中则是通过performSelectorOnMainThread 方法与主线程进行沟通,从而达到更新UI的目的。

之所以我们在写东西的时候会用到线程,是因为一些耗时或者需要频繁更新UI的操作如果放在主线程中执行的话,会让应用变得很卡,甚至被系统给kill掉,比如不可能在下载文件的时候手机就处于不可用的状态吧!多线程的出现就是为了避免这种情况的发生。

今天写这个demo就是为了理解多线程的概念并记录下一些NSThread的基本操作。总共开启了3个子线程,其中两个线程陷入死循环模拟耗时操作,并由bool变量run控制同步更新UI操作。另外一个线程则实现了从网上下载图片并将图片作为应用的背景的操作,这是一个真实的耗时操作。惯例,先看效果图,然后上代码;

iOS学习笔记---利用NSThread实现异步更新UI和下载图片_第1张图片iOS学习笔记---利用NSThread实现异步更新UI和下载图片_第2张图片iOS学习笔记---利用NSThread实现异步更新UI和下载图片_第3张图片

//
//  ViewController.m
//  Thread_Test
//
//  Created by yaodd on 13-7-10.
//  Copyright (c) 2013年 jitsun. All rights reserved.
//  这个demo完全是为了理解ios的多线程编程而做的一个练习,没什么实际用途

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize threadButton1;
@synthesize threadButton2;
@synthesize threadLabel1;
@synthesize threadLabel2;
@synthesize thread1;
@synthesize thread2;
@synthesize thread3;
@synthesize downloadImageButton;
@synthesize imageView;
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    NSString *imageUrl = @"http://www.zglxw.com/uploads/allimg/110612/141RG5M-0.jpg";//图片url
    //count用于更新UI状态标识
    count1 = 0;
    count2 = 0;
    //run用于控制线程内部操作
    run1 = NO;
    run2 = NO;
    //三个线程的初始化
	thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadEvent1) object:nil];
    [thread1 start];//开启线程1
    thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(threadEvent2) object:nil];
    [thread2 start];//开启线程2
    thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(downLoadImage:) object:imageUrl];
    
    
    
    //三个按钮添加响应
    [threadButton1 addTarget:self action:@selector(button1Pressed:) forControlEvents:UIControlEventTouchUpInside];
    [threadButton2 addTarget:self action:@selector(button2Pressed:) forControlEvents:UIControlEventTouchUpInside];
    
    [downloadImageButton addTarget:self action:@selector(downloadImagePressed:) forControlEvents:UIControlEventTouchUpInside];
    
    
}
//线程1的启动和暂停
- (void)button1Pressed:(id)sender
{
    if (run1) {
        [threadButton1 setTitle:@"启动第一个线程" forState:UIControlStateNormal];
        run1 = NO;
        
    } else {
        [threadButton1 setTitle:@"暂停第一个线程" forState:UIControlStateNormal];
        run1 = YES;
        
    }
}
//线程2的启动和暂停
- (void)button2Pressed:(id)sender
{
    if (run2) {
        [threadButton2 setTitle:@"启动第二个线程" forState:UIControlStateNormal];
        run2 = NO;
        
    } else {
        [threadButton2 setTitle:@"暂停第二个线程" forState:UIControlStateNormal];
        run2 = YES;
        
    }

}
//开启线程3
- (void)downloadImagePressed:(id)sender
{
    [thread3 start];
}
//线程1的处理事件
- (void)threadEvent1
{
    
    while (YES) {//死循环代表线程操作
        
        if (run1) {//用run控制线程。当run为真时更新UI,
            [NSThread sleepForTimeInterval:1];//延迟1秒
            [self performSelectorOnMainThread:@selector(updateUI1) withObject:nil waitUntilDone:YES];
        }
       
    }
   
}
- (void)threadEvent2
{
    while (YES) {
        
        if (run2) {
            [NSThread sleepForTimeInterval:0.5];
            [self performSelectorOnMainThread:@selector(updateUI2) withObject:nil waitUntilDone:YES];
        }
        
    }
    
}
//更新UI,该表label的值
- (void)updateUI1
{
    
    threadLabel1.text = [[NSString alloc]initWithFormat:@"%d",count1++];
}


- (void)updateUI2
{
   
    threadLabel2.text = [[NSString alloc]initWithFormat:@"%d",count2++];
}
//下载图片
- (void)downLoadImage:(NSString *)imageUrl
{
    NSData *data = [[NSData alloc] initWithContentsOfURL:
                   [NSURL URLWithString:imageUrl]];
    UIImage *image = [[UIImage alloc]initWithData:data];
    if (image == nil) {
        NSLog(@"图片下载失败!");
    } else {
        [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];
    }
}
//加载图片
- (void)updateImage:(UIImage *)image
{
    [imageView setImage:image];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

完整工程移步 http://download.csdn.net/detail/kekeqiaokeli/5732075 下载,谢谢支持!

好好学习,天天向上~··!

你可能感兴趣的:(iOS)