iOS整理 -- 多线程之NSThread

来源:互联网 发布:从python开始学编程pdf 编辑:程序博客网 时间:2024/04/30 11:13

多线程 —- NSThread

3种创建线程的方式 : NSThread , NSOperation , GCD

  • 1> NSThread 有两种直接创建方式:

    实例方法:
    (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
    类方法:
    (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

/**     *  开辟线程     *     *  @param SEL 监听实现方法     *  @param target selector消息发送的对象     *  @param object 传输给target的唯一参数,可以是nil     */    // 实例方法    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil];    // 类方法    [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil];    // 开启线程    [thread start];
  • 2> 不显式创建线程的方法: 开启后台执行的任务方法

    用NSObject的类方法 performSelectorInBackground:withObject: 创建一个线程:
    [Obj performSelectorInBackground:@selector(doSomething) withObject:nil];

  • 3>线程间通讯: 在后台线程通知主线程执行任务

    performSelectorOnMainThread:(SEL) withObject:(id) waitUntilDone:(BOOL)
    performSelectorOnMainThread是NSObject的方法,除了可以更新主线程的数据外,还可以更新其他线程的比如:
    用:performSelector:onThread:withObject:waitUntilDone:

  • 4>线程休眠(延迟时间)

    [NSThread sleepForTimeInterval:3];

  • 5>线程跟踪 (当前的执行线程)

    [NSThread currentThread];

    使用NSThread时,开启线程 和 关闭线程 都需要手动
    [thread start] 手动启动
    [thread start] 手动关闭

这里是一个简单的NSThread的应用小Demo,简单介绍了NSThread的基本使用.

首先,在storyBoard里面拖拽了一个UIIMageView控件,和一个UIButton控件,
接下来,就是代码的实现部分,由于功能简单,只是使用NSThread的创建,以及一些方法的实现.

#import "ViewController.h"#define kUrl @"http://i6.topit.me/6/5d/45/1131907198420455d6o.jpg"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imgView;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // 下载图片,完成之后通知刷新UI    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImageWithUrl:) object:kUrl];    [thread start];}- (void)downloadImageWithUrl:(NSString *)url{//    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];    NSURL *URL = [NSURL URLWithString:url];    NSData *data = [[NSData alloc] initWithContentsOfURL:URL];    UIImage *image = [[UIImage alloc] initWithData:data];    if (image != nil) {  // 图片下载成功        [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];    }}- (void)updateUI:(UIImage *)image{    self.imgView.image = image;}#pragma ----------------------------------------------------------------- (IBAction)click:(UIButton *)sender {    // NSThread    // 开辟线程    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil];    // 开启线程    [thread start];}- (void)threadAction{    for (int i = 0; i < 10; i++) {        NSLog(@"%@ ------- %d",[NSThread currentThread],i);    }}@end

实现效果:
这里写图片描述

0 0
原创粉丝点击