前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS学习系列之多线程—NSThread(一)

iOS学习系列之多线程—NSThread(一)

作者头像
roc
发布2018-03-30 14:52:21
1.3K0
发布2018-03-30 14:52:21
举报
文章被收录于专栏:iOS开发笔记iOS开发笔记

iOS线程模型

1

NSThread:objective-c线程库

2

Blocks/GCD: Blocks模式的线程池

3

NSOperationQueue: 线程池/线程队列

今天就先从NSThread学起吧!

NSThread

NSThread是轻量级的多线程开发,使用起来也并不复杂,但是使用NSThread需要自己管理线程生命周期。

1NSThread的初始化

/*

@method

@abstract 初始化方法

@discussion 创建线程之后就自动运行Selector方法

@param selector:线程执行的方法,这个selector最多只能接受一个参数

@param target:selector消息发送的对象

@param argument:传给Secletor的唯一参数,也可以为nil

@resault

*/

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

贴了段代码如下:

运行结果:

证明argument是传给Secletor的唯一参数。

//此方法需要创建后主动调用

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadMethod) object:nil];

[thread start];

//隐式创建线程的方法

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

2NSThread常用的操作

//获取当前线程

NSThread *current =[NSThread currentThread];

//获取主线程

NSThread *mainThread = [NSThread mainThread];

贴段代码:

打印:

PS:获取当前线程和主线程的方法,是获取执行当前方法对象的线程!

//暂停当前线程

1.[NSThread sleepForTimeInterval:10.0];

2.NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];

[NSThread sleepUntilDate:date];

PS:暂停线程的方法,是获取执行当前方法对象的线程!

//监听线程执行完成 关键字:NSThreadWillExitNotification

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(test:) name:NSThreadWillExitNotification object:nil];

贴段代码

结果:

3‍线程间的通信

//在指定线程上执行操作

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

//在主线程上执行操作

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

//在当前线程执行操作

- (id)performSelector:(SEL)aSelector withObject:(id)object;

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-12-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 iOS开发笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档