IOS中的线程操作(1)
来源:互联网 发布:godaddy ssl nginx 编辑:程序博客网 时间:2024/06/05 00:12
IOS 上提供的多线程方法只要分为三种,1、NSThread 2、NSOperation 3、GCD ([self performSelectorInBackground:SEL withObject:id] 这个方法本质上也是一种多线程的方式),三种方式抽象程度越来越高,代码的编写难度也越来越简单。
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
1 0
- IOS中的线程操作(1)
- IOS中的线程操作(2)
- IOS中的线程操作(3)
- iOS线程操作
- C#中的线程操作
- android中的线程操作
- C#中的线程操作
- IOS-线程异步操作GCD
- IOS-线程异步操作dispatch_queue_t
- IOS-线程异步操作GCD
- iOS子线程操作总结
- iOS中的文件操作
- iOS中的数据库操作
- Java中的线程操作0
- 线程基础:线程(2)——JAVA中的基本线程操作(上)
- 线程基础:线程(3)——JAVA中的基本线程操作(中)
- 线程基础:线程(4)——JAVA中的基本线程操作(下)
- 线程基础:线程(2)——JAVA中的基本线程操作(上)
- struts1、strutts2、springmvc三者区别
- Mybatis与Hibernate的区别
- Lucene的工作原理
- 数据库字符编码集查看命令
- linux常用命令
- IOS中的线程操作(1)
- 高并发处理方案
- ionic使用记录----popup
- leetcode 17 -- Letter Combinations of a Phone Number
- [置顶] Android Device Chooser 找不到真机设备问题
- 图灵机器人API接入
- solrcloud伪集群安装配置
- LINUX之awk命令
- Writing Better T-SQL: Top-Down Design May Not be the Best Choice