您的位置:首页 > 移动开发 > IOS开发

iOS线程其一NSThread

2016-04-15 09:26 477 查看
之前的文章,我简单分别介绍了四种线程。现在介绍其中一种的NSThread怎么用

//大多数方法默认都在主线程

这是一个触摸模拟器就会响应的方法

第一种《《《《《《《《《《《《

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//创建线程

//object参数

NSThread *thread = [[NSThread
alloc]initWithTarget:self
selector:@selector(run:)
object:@"jack"];

//启动线程

[thread start];

//线程一启动,就会在线程thread中执行self的run方法

thread.name = @"my - thread";

//是否在主线程

[thread isMainThread];

}

- (void)run:(NSString *)param{

NSLog(@"-------run------%@-----%@",param,[NSThread
currentThread]);

}

打印结果

//这个线程做完就会死掉

接下来,我们来证明线程是否会死掉
第一步.创建一个新的类.h.m
继承NSThread

在新建的XMGThread文件中写

#import "XMGThread.h"

@implementation XMGThread

- (void)dealloc{

NSLog(@"dealloc");

}

@end

第二步.在ViewController里引入头文件

#import "XMGThread.h"

把NSThread 全部改成 XMGThread 运行一下。打印出来的结果

说明线程走完会死掉
第二种《《《《《《《《《《《《

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

[self
createThread2];

}

- (void)createThread2{

//在主线程直接分出一条线程
创建新的线程

[NSThread
detachNewThreadSelector:@selector(run:)
toTarget:self
withObject:@"rose"];

}

第三种《《《《《《《《《《《《

//大多数方法默认都在主线程

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

[self
createThread3];

}

- (void)createThread3{

//开一个后台线程
子线程

[self
performSelectorInBackground:@selector(run:)
withObject:@"jack"];

}

//第二,第三种
不用alloc init一个线程

//优点简单快捷

//缺点
无法对线程更详细设置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: