NSOperation的使用细节 [2]
这一节我们来写自定义nonconcurrent的operation,自定义nonconcurrent的operation很简单,重写main方法,之后处理好cancel事件即可。
在开始写nonconcurrent的operation之前,我们需要先了解几个关于NSOperationQueue的细节。
挂起操作
通常情况下,将操作添加到队列中是会立马执行的(如果没有设置队列的最大并发数目),将suspended设置成YES后会将没有执行的operation全部挂起。
NSOperationQueue无法重复添加NSOperation
并且,NSOperationQueue也无法移除已经添加的操作
NSOperationQueue的cancelAllOperations仅仅是将所有的NSOperation的isCancelled置位为YES而已(NSOperation自身的cancel操作也是将isCancelled设置成YES)
我们可以通过设置NSOperationQueue的maxConcurrentOperationCount来让操作按照添加顺序执行
注意哦,NSOperationQueue并不能将单个的NSOperation进行挂起操作,NSOperation自身也无法将自己暂停后再进行恢复操作,当NSOperation取消了之后,你再也无法对其进行恢复操作了,在NSOperationQueue上,你是无法实现的。
以下提供源码
//
// NonconcurrentOperation.h
// NSOperationExample
//
// Created by YouXianMing on 15/9/4.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NonconcurrentOperation : NSOperation
@property (nonatomic, strong) NSString *urlString;
@property (nonatomic, strong, readonly) NSData *netData;
@end
//
// NonconcurrentOperation.m
// NSOperationExample
//
// Created by YouXianMing on 15/9/4.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
//
#import "NonconcurrentOperation.h"
@interface NonconcurrentOperation ()
@property (nonatomic, strong) NSData *netData;
@property (nonatomic) BOOL isDone;
@end
@implementation NonconcurrentOperation
- (void)main {
if ([self isCancelled] == YES || [self isDone] == YES) {
return;
}
NSURL *url = [NSURL URLWithString:_urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.netData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
if (self.netData) {
self.isDone = YES;
}
[self showThread];
}
- (void)showThread {
if ([NSThread currentThread].isMainThread == YES) {
NSLog(@"Run in MainThread %@", self.name);
} else {
NSLog(@"Run in SubThread %@", self.name);
}
}
@end
//
// ViewController.m
// NSOperationExample
//
// Created by YouXianMing on 15/9/4.
// Copyright (c) 2015年 YouXianMing. All rights reserved.
//
#import "ViewController.h"
#import "NonconcurrentOperation.h"
@interface ViewController () {
NonconcurrentOperation *operation1;
NonconcurrentOperation *operation2;
}
@property (nonatomic, strong) NSOperationQueue *queue;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = [[NSOperationQueue alloc] init];
self.queue.maxConcurrentOperationCount = 2;
// 操作1
operation1 = [[NonconcurrentOperation alloc] init];
operation1.urlString = @"http://pic.cnblogs.com/avatar/607542/20150807105148.png";
operation1.name = @"operation1";
// 操作2
operation2 = [[NonconcurrentOperation alloc] init];
operation2.urlString = @"http://pic.cnblogs.com/avatar/615197/20150505132152.png";
operation2.name = @"operation2";
[self.queue addOperation:operation1];
[self.queue addOperation:operation2];
[self performSelector:@selector(event) withObject:nil afterDelay:1.f];
}
- (void)event {
NSLog(@"%@", self.queue.operations);
}
@end