iOS学习笔记--02 多线程

来源:互联网 发布:企业网站seo外包 编辑:程序博客网 时间:2024/05/16 12:24

iOS的有三种多线程技术:

(一)NSThread
(二)Cocoa Operation
(三)GCD(全称:Grand Central Dispatch
以上三种技术,抽象程度从低到高。抽象程度越高,当然使用起来越简单好用。后者也是苹果较为推荐的方式。

(一)NSThread

两种实现方式:
1)实例方法

- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullableid)argument;

2)类方法

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


ps:所谓的实例方法,就是需要实例化一个对象,使用该对象进行调用。而类方法则直接使用类名调用的方式。

参数的意义:
selector :线程执行的方法,这个selector只能有一个参数,而且不能有返回值。
target  :selector消息发送的对象
argument:传输给target的唯一参数,也可以是nil
 
第一种方式是先创建线程对象,然后再运行线程操作,在运行线程操作前可以设置线程的优先级等线程信息;
第二种方式会直接创建线程并且开始运行线程。

下面是两种方式的实现示例:
1)实例方法实现:

- (void)viewDidLoad {    [super viewDidLoad];    NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(doSomething) object:nil];    [myThread start];}-(void)doSomething{    NSLog(@"新线程:%@",[NSThread currentThread]);}

2)类方法实现:

- (void)viewDidLoad {    [super viewDidLoad];    NSLog(@"主线程%@",[NSThread currentThread]);    [NSThread detachNewThreadSelector:@selector(doSomething) toTarget:self withObject:nil];}-(void)doSomething{    NSLog(@"新线程:%@",[NSThread currentThread]);}

下面是下载图片的例子:
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property (weak, nonatomic) IBOutlet UIImageView *myImageView;@end

#import "ViewController.h"#define imgUrl @"http://c.hiphotos.baidu.com/image/w%3D310/sign=4b3d50d58813632715edc432a18ea056/d52a2834349b033b015730d317ce36d3d439bdd8.jpg"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];//    NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(downLoadImg) object:nil];//    [myThread start];    NSLog(@"主线程%@",[NSThread currentThread]);    [NSThread detachNewThreadSelector:@selector(downLoadImg) toTarget:self withObject:nil];}-(void)downLoadImg{    NSLog(@"新线程:%@",[NSThread currentThread]);    NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imgUrl]];    UIImage *image = [[UIImage alloc]initWithData:data];    if (image) {        //通知主线程更新UI        [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];    }}-(void)updateUI:(UIImage*)image{    self.myImageView.image = image;}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];}

其中,线程间的通讯:通知主线程更新UI
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
除了更新主线程,也可以指定其他线程:
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;




未完待续。


参考:http://www.cocoachina.com/industry/20140520/8485.html
说明:本笔记作为学习记录用,无意侵权。所有引用皆会在参考处说明。












0 0