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

iOS中的多线程

2016-05-09 00:00 405 查看
多线程

第一种:NSThread

#import "ViewController.h"

@interface ViewController ()

//这里通过界面拖动创建了一个UIImageView,用于将多线程的图片显示在界面上
@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//创建多线程,添加一个方法,object传的参数是一个图片的网址
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(loadData:) object:@"http://pic4.nipic.com/20091102/3530505_133139096223_2.jpg"];

//开启多线程
[thread start];

}

-(void)loadData:(NSString *)str{

//**********这里注意:Xcode在工作中往往会出现无法兼容网址,所以要在app的加载里进行设置(在Info.plist文件中添加 App Transport Security Settings ,并且在其子列表中创建Allow Arbitrary Loads,选择Boolean为YES,这样可以正常引用链接。)

//先将上面多线程中传的 NSString 转成 NSURL 类型的,
//再将 NSURL 转成 NSData 类型的
//再将 NSData 转成 UIImage 类型的
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];

//如果图片生成成功
if (img) {
//回到主线程,更新UI(这里的方法是将上面转换类型生成的图片,添加到界面上的 UIImageView 上)
[self performSelectorOnMainThread:@selector(setImg:) withObject:img waitUntilDone:YES];
}

}

//将图片添加到界面上的 UIImageView 上的方法(实现)
-(void)setImg:(UIImage *)img{

[self.imgView setImage:img];

}


第二种:NSOperation

#import "ViewController.h"

@interface ViewController ()

//通过界面拖动,创建了一个UIImageView,用于显示线程中的图片
@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//创建线程队列
NSOperationQueue *op = [[NSOperationQueue alloc]init];

//创建线程
NSBlockOperation *bop = [NSBlockOperation blockOperationWithBlock:^{
[self loadImg:@"http://pic4.nipic.com/20091102/3530505_133139096223_2.jpg"];
}];

//把线程添加到队列中
[op addOperation:bop];

}

//线程的方法
-(void)loadImg:(NSString *)str{

//**********这里注意:Xcode在工作中往往会出现无法兼容网址,所以要在app的加载里进行设置(在Info.plist文件中添加 App Transport Security Settings ,并且在其子列表中创建Allow Arbitrary Loads,选择Boolean为YES,这样可以正常引用链接。)

//先将上面多线程中传的 NSString 转成 NSURL 类型的,
//再将 NSURL 转成 NSData 类型的
//再将 NSData 转成 UIImage 类型的
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];

//如果图片生成成功
if (img) {
//回到主线程,更新UI
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
//小细节: 将图片添加到界面上的UIImageView上,两种方法

//            //第一种,直接添加
//            [self.imgView setImage:img];

//第二种,通过方法添加
[self setImg:img];

}];

}

}

//第二种,将图片添加到UIImageView上的方法
-(void)setImg:(UIImage *)img{

[self.imgView setImage:img];

}


第三种:Grand Central Dispatch (GCD)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: