您的位置:首页 > 移动开发 > IOS开发

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方法

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: