首页 技术 正文
技术 2022年11月20日
0 收藏 724 点赞 4,816 浏览 1507 个字
一、创建多线程的五种方式

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.开启线程的方法四

IOS开发中多线程的使用

    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
for(int i=0;i<50;i++){
printf("子线程\n");
}
}];

IOS开发中多线程的使用

5.开启线程的方法五

IOS开发中多线程的使用

    //第一步开启线程池
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];

IOS开发中多线程的使用

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

1.核心思想

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

2.实现思路

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

  主要代码:

IOS开发中多线程的使用

#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]; }
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,486
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,126
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,287