iOS多线程与网络开发之NSOperation
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载。
假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额任意,重在心意^_^
我要捐赠: 点击捐赠
Cocos2d-X源代码下载:点我传送
游戏官方下载:
http://dwz.cn/RwTjl
游戏视频预览:
http://dwz.cn/RzHHd
游戏开发博客:
http://dwz.cn/RzJzI
游戏源代码传送:
http://dwz.cn/Nret1
NSOperation和NSOperationQueue实现多线程的详细步骤
先将须要运行的操作封装到一个NSOperation对象中
然后将NSOperation对象加入到NSOperationQueue中
系统会自己主动将NSOperationQueue中的NSOperation取出来
将取出的NSOperation封装的操作放到一条新线程中运行
使用NSOperation子类的方式有3种
NSInvocationOperation
NSBlockOperation
自己定义子类继承NSOperation,实现内部对应的方法
- (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg;
调用start方法開始运行操作
- (void)start;
一旦运行操作,就会调用target的sel方法
注意
默认情况下,调用了start方法后并不会开一条新线程去运行操作。而是在当前线程同步运行操作
仅仅有将NSOperation放到一个NSOperationQueue中,才会异步运行操作
+ (id)blockOperationWithBlock:(void (^)(void))block;
通过addExecutionBlock:方法加入很多其它的操作
- (void)addExecutionBlock:(void (^)(void))block;
注意:仅仅要NSBlockOperation封装的操作数 > 1。就会异步运行操作
NSOperation能够调用start方法来运行任务。但默认是同步运行的
假设将NSOperation加入到NSOperationQueue(操作队列)中。系统会自己主动异步运行NSOperation中的操作
加入操作到NSOperationQueue中
- (void)addOperation:(NSOperation *)op;
- (void)addOperationWithBlock:(void (^)(void))block;
同一时候运行的任务数
比方。同一时候开3个线程运行3个任务,并发数就是3
最大并发数的相关方法
- (NSInteger)maxConcurrentOperationCount;
- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;
- (void)cancelAllOperations;
提示:也能够调用NSOperation的- (void)cancel方法取消单个操作
暂停和恢复队列
- (void)setSuspended:(BOOL)b; // YES代表暂停队列,NO代表恢复队列
- (BOOL)isSuspended;
- (NSOperationQueuePriority)queuePriority;
- (void)setQueuePriority:(NSOperationQueuePriority)p;
优先级的取值
NSOperationQueuePriorityVeryLow = -8L,
NSOperationQueuePriorityLow = -4L,
NSOperationQueuePriorityNormal = 0,
NSOperationQueuePriorityHigh = 4,
NSOperationQueuePriorityVeryHigh = 8
比方一定要让操作A运行完后,才干运行操作B,能够这么写
[operationB addDependency:operationA]; // 操作B依赖于操作A
能够在不同queue的NSOperation之间创建依赖关系
- (void (^)(void))completionBlock;
- (void)setCompletionBlock:(void (^)(void))block;
重写- (void)main方法,在里面实现想运行的任务
重写- (void)main方法的注意点
自己创建自己主动释放池(由于假设是异步操作,无法訪问主线程的自己主动释放池)
常常通过- (BOOL)isCancelled方法检測操作是否被取消,对取消做出响应

//
// HVWDownloadImageOperation.h
// ConcurrentDownloadImageDemo
//
// Created by YuriyHao on 15/7/24.
// Copyright (c) 2015年 YuriyHao. All rights reserved.
// #import <Foundation/Foundation.h> @class HVWDownloadImageOperation; @protocol HVWDownloadImageOperationDelegate <NSObject> @optional
- (void) downloadImageOperation:(HVWDownloadImageOperation *) operation didFinishedDownloadWithImage:(UIImage *) image; @end @interface HVWDownloadImageOperation : NSOperation @property(nonatomic, strong) NSString *url; @property(nonatomic, strong) NSIndexPath *indexPath; @property(nonatomic, weak) id<HVWDownloadImageOperationDelegate> delegate; @end
//
// HVWDownloadImageOperation.m
// ConcurrentDownloadImageDemo
//
// Created by YuriyHao on 15/7/24.
// Copyright (c) 2015年 YuriyHao. All rights reserved.
// #import <UIKit/UIKit.h>
#import "HVWDownloadImageOperation.h" @implementation HVWDownloadImageOperation - (void)main {
NSLog(@"====下载图片======%@", [NSThread currentThread]); NSURL *url = [NSURL URLWithString:self.url];
NSData *data;
for (int i=0; i<1; i++) {
data = [NSData dataWithContentsOfURL:url];
} UIImage *image = [UIImage imageWithData:data]; if ([self.delegate respondsToSelector:@selector(downloadImageOperation:didFinishedDownloadWithImage:)]) {
[self.delegate downloadImageOperation:self didFinishedDownloadWithImage:image];
}
} @end
//
// HVWApp.h
// ConcurrentDownloadImageDemo
//
// Created by YuriyHao on 15/7/24.
// Copyright (c) 2015年 YuriyHao. All rights reserved.
// #import <Foundation/Foundation.h> @interface HVWApp : NSObject @property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) NSString *icon;
@property(nonatomic, strong) NSString *download; - (instancetype) initWithDictionary:(NSDictionary *) dict;
+ (instancetype) appWithDictionary:(NSDictionary *) dict; @end
//
// ViewController.m
// ConcurrentDownloadImageDemo
//
// Created by YuriyHao on 15/7/24.
// Copyright (c) 2015年 YuriyHao. All rights reserved.
// #import "ViewController.h"
#import "HVWApp.h"
#import "HVWDownloadImageOperation.h" @interface ViewController () <UITableViewDataSource, UITableViewDelegate, HVWDownloadImageOperationDelegate> @property(nonatomic, strong) NSArray *apps; @property(nonatomic, strong) NSOperationQueue *queue; @property(nonatomic, strong) NSMutableDictionary *operations;
@property(nonatomic, strong) NSMutableDictionary *images; @end @implementation ViewController - (NSArray *)apps {
if (nil == _apps) {
NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil]]; NSMutableArray *appArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
HVWApp *app = [HVWApp appWithDictionary:dict];
[appArray addObject:app];
}
_apps = appArray;
}
return _apps;
} - (NSOperationQueue *)queue {
if (_queue == nil ) {
_queue = [[NSOperationQueue alloc] init];
_queue.maxConcurrentOperationCount = 3;
}
return _queue;
} - (NSMutableDictionary *)operations {
if (nil == _operations) {
_operations = [NSMutableDictionary dictionary];
}
return _operations;
} - (NSMutableDictionary *)images {
if (nil == _images) {
_images = [NSMutableDictionary dictionary];
}
return _images;
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} #pragma mark - tableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.apps.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"AppCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
} HVWApp *app = self.apps[indexPath.row];
cell.textLabel.text = app.name;
cell.detailTextLabel.text = app.download; // 占位图片
cell.imageView.image = [UIImage imageNamed:@"a9ec8a13632762d0092abc3ca2ec08fa513dc619"]; // 假设没有图片,准备开启线程下载图片
UIImage *image = self.images[app.icon]; if (image) {
// 假设图片存在,不须要反复下载,直接设置图片
cell.imageView.image = image;
} else { // 假设图片不存在。看看是不是正在下载
HVWDownloadImageOperation *operation = self.operations[app.icon]; if (operation) {
// 假设图片正在下载,不必要开启线的线程再进行下载
} else { // 没有在下载,创建一个新的任务进行下载
operation = [[HVWDownloadImageOperation alloc] init];
// 设置代理
operation.delegate = self;
// 传送url
operation.url = app.icon;
// 记录indexPath
operation.indexPath = indexPath; [self.queue addOperation:operation]; // 记录正在下载的任务
[self.operations setObject:operation forKey:operation.url];
}
} return cell;
} #pragma mark - HVWDownloadImageOperationDelegate
- (void)downloadImageOperation:(HVWDownloadImageOperation *)operation didFinishedDownloadWithImage:(UIImage *)image {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:operation.indexPath];
cell.imageView.image = image;
[self.tableView reloadRowsAtIndexPaths:@[operation.indexPath] withRowAnimation:UITableViewRowAnimationNone]; // 存储图片到内存
if (image) {
[self.images setObject:image forKey:operation.url];
} NSLog(@"已经下载的图片数==========>%d", self.images.count);
} @end
郝萌主倾心贡献,尊重作者的劳动成果。请勿转载。
假设文章对您有所帮助。欢迎给作者捐赠。支持郝萌主,捐赠数额任意,重在心意^_^
我要捐赠: 点击捐赠
Cocos2d-X源代码下载:点我传送
游戏官方下载:
http://dwz.cn/RwTjl
游戏视频预览:
http://dwz.cn/RzHHd
游戏开发博客:
http://dwz.cn/RzJzI
游戏源代码传送:
http://dwz.cn/Nret1
iOS多线程与网络开发之NSOperation的更多相关文章
- iOS多线程与网络开发之NSURLCache
郝萌主倾心贡献,尊重作者的劳动成果.请勿转载. // 2 // ViewController.m 3 // NSURLCacheDemo 4 // 5 // Created by haomengzhu ...
- iOS多线程开发之NSOperation - 快上车,没时间解释了!
一.什么是NSOperation? NSOperation是苹果提供的一套多线程解决方案.实际上NSOperation是基于GCD更高一层的封装,但是比GCD更加的面向对象.代码可读性更高.可控性更强 ...
- iOS多线程开发之NSOperation
一.什么是NSOperation? NSOperation是苹果提供的一套多线程解决方案.实际上NSOperation是基于GCD更高一层的封装,但是比GCD更加的面向对象.代码可读性更高.可控性更强 ...
- iOS多线程与网络开发之多线程概述
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠.支持郝萌主,捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 游戏官方下 ...
- iOS开发之NSOperation & NSOperationQueue
1.简介 (1) NSOperationQueue(操作队列)是由GCD提供的队列模型的Cocoa抽象,是一套Objective-C的API,为了使并发(多线程)编程变得更加简单,但效率比GCD略低. ...
- iOS网络开发之AFNetworking
概述 AFNetworking是一个非常受欢迎的轻量级的iOS.Mac OS X网络通信类库.它建立在NSURLConnection.NSOperation以及其技术的基础上,有着精心设计的模块结构和 ...
- iOS多线程编程Part 2/3 - NSOperation
多线程编程Part 1介绍了NSThread以及NSRunLoop,这篇Blog介绍另一种并发编程技术:NSOPeration. NSOperation & NSOperationQueue ...
- iOS多线程与网络开发之发送接收server信息
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. (1).使用同步方法发送get请求(不经常使用) 2 /** 发送get消息 */ 3 - (void) testGet { 4 NSString *r ...
- iOS多线程与网络开发之多线程NSThread
郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 游戏官方下 ...
随机推荐
- JAVA多线程和并发基础面试问答【转】
JAVA多线程和并发基础面试问答 多线程和并发问题是Java技术面试中面试官比较喜欢问的问题之一.在这里,从面试的角度列出了大部分重要的问题,但是你仍然应该牢固的掌握Java多线程基础知识来对应日后碰 ...
- Java:HttpClient篇,HttpClient4.2在Java中的几则应用:Get、Post参数、Session(会话)保持、Proxy(代理服务器)设置,多线程设置...
新版HttpClient4.2与之前的3.x版本有了很大变化,建议从http://hc.apache.org/处以得到最新的信息. 关于HttpCore与HttpClient:HttpCore是位于H ...
- Oracle学习笔记之五,Oracle 11g的PL/SQL入门
1. PL/SQL概述 PL/SQL(Procedural Language/SQL)是Oracle的专用语言,是对标准SQL语言的扩展,它允许在其内部嵌套普通的SQL语句,还可以定义变量和常量,允许 ...
- [javase学习笔记]-6.3 对象的内存体现
这一节我们来简单的看一看对象在内存中是什么样子呢,怎样体现. 我们以上一节的測试代码为例. 我们在函数的内存分配分析过.当该代码执行时,首先会载入主函数在栈内存中为main函数分配一个空间: 然后执行 ...
- 易懂的modelsim学习笔记
1. 建一个总文件夹,如cnt2. 为源代码,测试台文件,仿真各建一文件夹.如src,tb,sim3. 编写源代码,testbench.如cnt.v,tb_cnt.v文件,同时文件名里的模块名与文件名 ...
- linux服务器文件删除空间却未释放
在Linux或者Unix系统中,通过rm或者文件管理器删除文件将会从文件系统的目录结构上解除链接(unlink),然而如果文件是被打开的(有一个进程正在使用),那么进程将仍然可以读取该文件,磁盘空间也 ...
- [LeetCode][Java] Search Insert Position
题目: Given a sorted array and a target value, return the index if the target is found. If not, return ...
- 让一个div始终固定在页面的某一固定位置的方法
方法一:直接用position:fixed 方法二:写一个滚动条滚动事件,让这个div设置 position:absolute 该top的距离等于滚动的距离scrollTop() 写法如下:$(win ...
- 一款纯css实现的漂亮导航
今天给大家分享一款纯css实现的漂亮导航.之前为大家分享过jquery实现的个人中心导航菜单,今天这款也是适合放在个人中心.还带来图标,效果不错.一起看下效果图: 在线预览 源码下载 实现的代码. ...
- jacky自问自答-java并发编程
1.java Web中线程不是由tomcat这类web容器负责的吗?为什么还要我控制多线程? 答:这个问题很多初学者都会有的疑惑,举一个我以前做的一个需求,java作为中间平台,是socket服务端, ...