[iOS 多线程 & 网络 - 1.3] - NSOperation
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 hellovoidworld on 15/1/22.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import <Foundation/Foundation.h> @class HVWDownloadImageOperation; @protocol HVWDownloadImageOperationDelegate <NSObject> /** 代理方法,下载完成之后 */
@optional
- (void) downloadImageOperation:(HVWDownloadImageOperation *) operation didFinishedDownloadWithImage:(UIImage *) image; @end @interface HVWDownloadImageOperation : NSOperation /** 存储每个图片的url */
@property(nonatomic, strong) NSString *url; /** 要显示的cell的index */
@property(nonatomic, strong) NSIndexPath *indexPath; /** 代理 */
@property(nonatomic, weak) id<HVWDownloadImageOperationDelegate> delegate; @end
//
// HVWDownloadImageOperation.m
// ConcurrentDownloadImageDemo
//
// Created by hellovoidworld on 15/1/22.
// Copyright (c) 2015年 hellovoidworld. 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=; i<; 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 hellovoidworld on 15/1/22.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import <Foundation/Foundation.h> @interface HVWApp : NSObject /** app名字 */
@property(nonatomic, strong) NSString *name;
/** app图标url */
@property(nonatomic, strong) NSString *icon;
/** app的副标题--下载量 */
@property(nonatomic, strong) NSString *download; - (instancetype) initWithDictionary:(NSDictionary *) dict;
+ (instancetype) appWithDictionary:(NSDictionary *) dict; @end
//
// ViewController.m
// ConcurrentDownloadImageDemo
//
// Created by hellovoidworld on 15/1/22.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import "ViewController.h"
#import "HVWApp.h"
#import "HVWDownloadImageOperation.h" @interface ViewController () <UITableViewDataSource, UITableViewDelegate, HVWDownloadImageOperationDelegate> /** 所有app数据 */
@property(nonatomic, strong) NSArray *apps; /** 任务队列 */
@property(nonatomic, strong) NSOperationQueue *queue; /** 所有任务 */
@property(nonatomic, strong) NSMutableDictionary *operations; /** 所有图片 */
@property(nonatomic, strong) NSMutableDictionary *images; @end @implementation ViewController /** 加载plist文件,读取数据到模型,存储到数组中 */
- (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 = ;
}
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 ;
} - (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
/** 代理方法,图片下载完成后,显示到cell上 */
- (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
[iOS 多线程 & 网络 - 1.3] - NSOperation的更多相关文章
- [iOS 多线程 & 网络 - 1.0] - 多线程概述
A.进程 什么是进程进程是指在系统中正在运行的一个应用程序 每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内 比如同时打开QQ.Xcode,系统就会分别启动2个进程 通过"活 ...
- iOS 多线程 简单学习NSThread NSOperation GCD
1:首先简单介绍什么叫线程 可并发执行的,拥有最小系统资源,共享进程资源的基本调度单位. 共用堆,自有栈(官方资料说明iOS主线程栈大小为1M,其它线程为512K). 并发执行进度不可控,对非原子操作 ...
- [iOS 多线程 & 网络 - 2.0] - 发送接收 服务器信息
A.搭建java服务器 使用eclipse.tomcat和struts2框架搭建一个简单的服务器 1.准备好合适版本的JDK.eclipse EE.tomcat.struts2 框架包 2.配置JDK ...
- [iOS 多线程 & 网络 - 2.9] - ASI框架
A.ASI基本知识 1.ASI简单介绍 ASI:全称是ASIHTTPRequest,外号“HTTP终结者”,功能十分强大. ASI的实现基于底层的CFNetwork框架,因此运行效率很高. ASI的g ...
- [iOS 多线程 & 网络 - 2.8] - 检测网络状态
A.说明 在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的:(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验 ...
- [iOS 多线程 & 网络 - 2.3] - 解析xml
A.XML基本知识 1.xml概念 什么是XML全称是Extensible Markup Language,译作“可扩展标记语言”跟JSON一样,也是常用的一种用于交互的数据格式一般也叫XML文档(X ...
- [iOS 多线程 & 网络 - 2.1] - 解析json
A.iOS中json的基本使用 1.解析json数据 (1)json反序列化 对象{}格式 {key : value, key : value,...} 的键值对的结构可以反序列化为OC中的NSDic ...
- [iOS 多线程 & 网络 - 1.1] - 多线程NSThread
A.NSThread的基本使用 1.创建和启动线程 一个NSThread对象就代表一条线程创建.启动线程NSThread *thread = [[NSThread alloc] initWithTar ...
- [iOS 多线程 & 网络 - 4.0] - AFN框架简单使用
A.AFN基本知识 1.概念 AFNetworking 是对NSURLConnection的封装 运行效率没有ASI高(因为ASI基于CFNetwork),但是使用简单 AFN支持ARC B. ...
随机推荐
- C#中跨线程读取控件值、设置控件值
编写应用程序时,涉及到大量数据处理.串口通信.Socket通信等都会用到多线程,多线程中如何跨线程调用主界面或其他界面下的控件是一个问题,利用invoke和delegate可以解决. delegate ...
- 使用讯飞SDK,实现文字在线合成语音
private SpeechSynthesizer mTts; private int isSpeaking = 0; mTts= SpeechSynthesizer.createSynthesize ...
- [反汇编练习] 160个CrackMe之004
[反汇编练习] 160个CrackMe之004. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...
- PNG文件结构分析 ---Png解析
PNG文件结构分析 ---Png解析 为了实现更高级的应用,我们必须充分挖掘PNG的潜力. PNG的文件结构 根据PNG文件的定义来说,其文件头位置总是由位固定的字节来描述的: 十进制数 13 ...
- Hide Xcode8 strange log.
Product > Scheme > Edit Scheme Environment Variables set OS_ACTIVITY_MODE = disable
- memcachedd基础
系列文章导航: memcached完全剖析–1. memcached的基础 memcached全面剖析–2. 理解memcached的内存存储 memcached全面剖析–3. memcached的删 ...
- Android-监听sdcard状态
public class MyService extends Service { private static final String TAG = "MyService"; Fi ...
- 写的cursor demo仅作记录
declare @objectID int; declare objcur cursor for object_id from m_object open objcur fetch next from ...
- 如何在linux中搭建JEECMS系统
本人正在进行jeecms二次开发,但因win7系统中的Tomcat无法使用,就想起在linux下安装,但去jeecms的官方网站,没有给出在linux下安装的方法,确实苦恼,经过一天的研究,终于大功告 ...
- C# DataGridView的列对象属性探讨 (未完待续)
比较难的几个属性的释义[1]: