IOS开发中多线程的使用

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

一、创建多线程的五种方式

1.开启线程的方法一NSThread * thread=[[NSThread alloc] initWithTarget:self selector:@selector(_update)object:nil];

2.开启线程的方法二 [NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];

3.开启线程的方法三[self performSelectorInBackground:@selector(_update) withObject:nil];

4.开启线程的方法四NSOperationQueue *queue=[[NSOperationQueue alloc] init];

[queue addOperationWithBlock:^{for(inti=0;i<50;i++){PRintf("子线程\n");

}

}];

5.开启线程的方法五//第一步开启线程池NSOperationQueue * queue=[[NSOperationQueue alloc] init];//设置并发数目[queue setMaxConcurrentOperationCount:2];//第二部创建多线程添加到线程池NSInvocationOperation * thread1=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update1)object:nil];

NSInvocationOperation*thread2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update2)object:nil];

[thread1 setQueuePriority:NSOperationQueuePriorityVeryLow];

[thread2 setQueuePriority:NSOperationQueuePriorityVeryHigh];

[queue addOperation:thread1];

[queue addOperation:thread2];

二、多线程应用实例,加载图片。

1.核心思想考虑到如果加载网络图片会延迟,在一个主线程加载会影响控件的渲染,此时可以采取多线程,异步加载完成后刷新UI。

2.实现思路通过为UIImageView 增加类目来实现多线程下载。

主要代码:

#import"UIImageView+thread.h"@implementation UIImageView(load)- (void) setImageWithUrl:(NSString *)url{

[self performSelectorInBackground:@selector(_loadImage:) withObject:url];

}- (void) _loadImage:(NSString *)u{

@autoreleasepool {

NSURL*url=[NSURL URLWithString:u];

NSData*data=[NSData dataWithContentsOfURL:url];

UIImage*image=[UIImage imageWithData:data];

[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];

}

}

作者:杰瑞教育

出处:http://www.cnblogs.com/jerehedu/

本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航