首页 技术 正文
技术 2022年11月11日
0 收藏 428 点赞 2,519 浏览 1783 个字

使用 NSOperation的方式有两种,

一种是用定义好的两个子类:

NSInvocationOperation 和 NSBlockOperation。

另一种是继承NSOperation

如果你也熟悉Java,NSOperation就和java.lang.Runnable接口很相似。和Java的Runnable一样,NSOperation也是设计用来扩展的,只需继承重写NSOperation的一个方法main。相当与java 中Runnalbe的Run方法。然后把NSOperation子类的对象放入NSOperationQueue队列中,该队列就会启动并开始处理它。

NSInvocationOperation例子:

和前面一篇博文一样,我们实现一个下载图片的例子。新建一个Single View app,拖放一个ImageView控件到xib界面。

实现代码如下:

  1. #import “ViewController.h”
  2. #define kURL @”http://avatar.csdn.net/2/C/D/1_totogo2010.jpg”
  3. @interface ViewController ()
  4. @end
  5. @implementation ViewController
  6. – (void)viewDidLoad
  7. {
  8. [super viewDidLoad];
  9. NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self
  10. selector:@selector(downloadImage:)
  11. object:kURL];
  12. NSOperationQueue *queue = [[NSOperationQueue alloc]init];
  13. [queue addOperation:operation];
  14. // Do any additional setup after loading the view, typically from a nib.
  15. }
  16. -(void)downloadImage:(NSString *)url{
  17. NSLog(@”url:%@”, url);
  18. NSURL *nsUrl = [NSURL URLWithString:url];
  19. NSData *data = [[NSData alloc]initWithContentsOfURL:nsUrl];
  20. UIImage * image = [[UIImage alloc]initWithData:data];
  21. [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
  22. }
  23. -(void)updateUI:(UIImage*) image{
  24. self.imageView.image = image;
  25. }
  1. viewDidLoad方法里可以看到我们用NSInvocationOperation建了一个后台线程,并且放到NSOperationQueue中。后台线程执行downloadImage方法。
  2. downloadImage 方法处理下载图片的逻辑。下载完成后用performSelectorOnMainThread执行主线程updateUI方法。
  3. updateUI 并把下载的图片显示到图片控件中。

运行可以看到下载图片显示在界面上。

iOS多线程之NSOperation,NSOperationQueue

第二种方式继承NSOperation

在.m文件中实现main方法,main方法编写要执行的代码即可。

如何控制线程池中的线程数?

队列里可以加入很多个NSOperation, 可以把NSOperationQueue看作一个线程池,可往线程池中添加操作(NSOperation)到队列中。线程池中的线程可看作消费者,从队列中取走操作,并执行它。

通过下面的代码设置:
[queue setMaxConcurrentOperationCount:5];
线程池中的线程数,也就是并发操作数。默认情况下是-1,-1表示没有限制,这样会同时运行队列中的全部的操作。

著作权声明:本文由http://blog.csdn.net/totogo2010/原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!

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