简要咨询咨询QQ网站导航网站搜索手机站点联系我们设为首页加入收藏 

IOS开发中多线程的使用

来源:易贤网   阅读:1659 次  日期:2015-04-21 13:53:59

温馨提示:易贤网小编为您整理了“IOS开发中多线程的使用”,方便广大网友查阅!

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

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(int i=0;i<50;i++){

printf("子线程 ");

}

}];

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];

}

}

更多信息请查看IT技术专栏

更多信息请查看技术文章
点此处就本文及相关问题在本站进行非正式的简要咨询(便捷快速)】     【点此处查询各地各类考试咨询QQ号码及交流群
上一篇:android studio从1.1正式版升级到1.2 Preview 3报错
下一篇:PHP开发的一般流程
易贤网手机网站地址:IOS开发中多线程的使用
由于各方面情况的不断调整与变化,易贤网提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!