深入浅出 iOS 之多线程 NSThread
2015-12-26 21:25
477 查看
每个iOS应用程序都有个专门用来更新显示UI界面、处理用户的触摸事件的主线程,因此不能将其他太耗时的操作放在主线程中执行,不然会造成主线程堵塞(出现卡机现象),带来极坏的用户体验。一般的解决方案就是将那些耗时的操作放到另外一个线程中去执行,多线程编程是防止主线程堵塞,增加运行效率的最佳方法。
iOS支持多个层次的多线程编程,层次越高的抽象程度越高,使用也越方便,也是苹果最推荐使用的方法。下面根据抽象层次从低到高依次列出iOS所支持的多线程编程方法:
1、Thread :是三种方法里面相对轻量级的,但需要管理线程的生命周期、同步、加锁问题,这会导致一定的性能开销
2、Cocoa Operations:是基于OC实现的,NSOperation以面向对象的方式封装了需要执行的操作,不必关心线程管理、同步等问题。NSOperation是一个抽象基类,iOS提供了两种默认实现:NSInvocationOperation和NSBlockOperation,当然也可以自定义NSOperation
3、Grand Central Dispatch(简称GCD,iOS4才开始支持):提供了一些新特性、运行库来支持多核并行编程,它的关注点更高:如何在多个cpu上提升效率
一、NSThread的初始化
1、动态方法
-(id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;// 初始化线程 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; // 设置线程的优先级(0.0 - 1.0,1.0最高级) thread.threadPriority = 1; // 开启线程 [thread start];
参数解析: selector :线程执行的方法,这个selector最多只能接收一个参数 target :selector消息发送的对象 argument : 传给selector的唯一参数,也可以是nil
2、静态方法
+(void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil]; - // 调用完毕后,会马上创建并开启新线程
3.隐式创建线程的方法
[self performSelectorInBackground:@selector(run) withObject:nil];
二、获取当前线程
NSThread *current = [NSThread currentThread];
三、获取主线程
NSThread *main = [NSThread mainThread];
四、暂停当前线程
// 暂停2s [NSThread sleepForTimeInterval:2]; // 或者 NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]; [NSThread sleepUntilDate:date];
五、线程间的通信
1、在指定线程上执行操作
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
2、在主线程上执行操作
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
3、在当前线程执行操作
[self performSelector:@selector(run) withObject:nil];
六、优缺点
1、优点
优点:NSThread比其他两种多线程方案较轻量级,更直观地控制线程对象2、缺点
缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销相关文章推荐
- iOs真机调试时编译问题
- iOS开发——图形编程OC篇&(二)CALayer自定义图层
- iOS scrollview中添加button
- iOS开发——图形编程OC篇&(一)CALayer介绍与基本使用
- iOS scrollview的实现
- Ubuntu14.04 使用visualBox安装虚拟机出现VT-x is disabled in the BIOS错误
- iOS学习笔记53-Xcode设置项之Architectures和Valid Architectures
- iOS ARC也会有内存泄露
- iOS 用collectionview 做的无限图片滚动 广告banner适用
- iOS中的事件,手势识别
- iOS支付宝支付--密钥制作
- iOS开发之Git的命令以及xocde打不开的原因
- 工作记录8:iOS 传值问题总结(7种传值完美介绍)
- iOS 各种传值方式
- ios中两个viewcontroller之间如何传递数据
- 如何集成inmobi到ios
- iOS中的手势详解
- [IOS开发教程] iOS获取设备信息
- iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例)
- iOS Label的图文混排