IOS中的线程操作(1)
2015-06-03 10:50
357 查看
IOS 上提供的多线程方法只要分为三种,1、NSThread 2、NSOperation 3、GCD ([self performSelectorInBackground:SEL withObject:id] 这个方法本质上也是一种多线程的方式),三种方式抽象程度越来越高,代码的编写难度也越来越简单。
1、NSThread:
NSThread比其他两个都要更轻量级,但需要自己来管理线程的生命周期和同步,代码的编写上比其他两个复杂。
NSThread提供了两种初始化方式,一种是传统的init方法
在init的时候,虽然已经为该线程分配了内存,不过该线程并不会立刻执行,使用这种方法去初始化优点显而易见,我们可以得到一个NSThread对象,可以方便的进行对该线程的管理。
而另外一种方法
使用这种方式开启线程,这个线程会立刻执行
看下面的代码,大家都知道访问网络是一个耗时的操作,在项目中我们需要展现从网络中获取的图片的时候我们就可以使用线程操作
1、NSThread:
NSThread比其他两个都要更轻量级,但需要自己来管理线程的生命周期和同步,代码的编写上比其他两个复杂。
NSThread提供了两种初始化方式,一种是传统的init方法
NSThread *thread = [[NSThread alloc] initWithTarget:(id) selector:(SEL) object:(id)] [thread start];
在init的时候,虽然已经为该线程分配了内存,不过该线程并不会立刻执行,使用这种方法去初始化优点显而易见,我们可以得到一个NSThread对象,可以方便的进行对该线程的管理。
而另外一种方法
[NSThread detachNewThreadSelector:(SEL) toTarget:(id) withObject:(id)]
使用这种方式开启线程,这个线程会立刻执行
看下面的代码,大家都知道访问网络是一个耗时的操作,在项目中我们需要展现从网络中获取的图片的时候我们就可以使用线程操作
#import "ViewController.h" #define IMAGE_PATH @"https://www.baidu.com/img/bdlogo.png" @interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *mImage; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSThread *mThread = [[NSThread alloc] initWithTarget:self selector:@selector(DownImage:) object:IMAGE_PATH]; [mThread start]; } - (void)DownImage:(NSString *)imagePath{ NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imagePath]]; UIImage *image = [[UIImage alloc] initWithData:imageData]; [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES]; } - (void)setImage:(UIImage *)image{ [self.mImage setImage:image]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
相关文章推荐
- 30多个iOS常用动画,带详细注释
- iOS - 需求 - 将参数进行字典排序组成字符串(待签名字符串)
- 使用Xcode和Instruments调试解决iOS内存泄露
- iOS:KVO的概述与使用
- iOS容易造成循环引用的三种场景之Block以及对应的使用方法(二)
- Autolayout及VFL经验分享【更新ing】
- iOS 彻底学会使用delegate
- iOS NSNotification的使用
- ios之下拉刷新上拉加载更多
- iOS开发系列--音频播放、录音、视频播放、拍照、视频录制
- iOS推送生成服务器端p12文件
- iOS 内存管理笔记
- iOS-cornerstone破解版
- iOS开发 LaunchImage和LaunchScreen.xib
- git - 简易指南
- git - 简易指南
- imageNamed 与 imageWithContentsOfFile的区别
- imageNamed 与 imageWithContentsOfFile的区别
- 详解OS X和iOS图像处理框架Core Image
- 【iOS】学习材料