NSOperation相关使用介绍
NSOperation 一一 基础使用
@implementation ViewController
#pragma mark - 懒加载
- (NSOperationQueue *)quque{
if (_quque == nil) {
_quque = [[NSOperationQueue alloc] init];
}
return _quque;
}
#pragma mark - 基本概念
#pragma mark - UITouch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self test7];
}
#pragma mark - 高级操作
- (void)test7{
NSBlockOperation * operationA = [NSBlockOperation blockOperationWithBlock:^{
[self longtimeOperation:@10];
}];
NSBlockOperation * operationB = [NSBlockOperation blockOperationWithBlock:^{
[self longtimeOperation:@20];
}];
[operationB setCompletionBlock:^{
NSLog(@"操作B结束");
NSLog(@"++:%@", [NSThread currentThread]);
}];
[operationA addDependency:operationB];
[self.quque addOperations:@[operationB, operationA] waitUntilFinished:NO];
}
- (IBAction)cancel:(id)sender {
[self.quque cancelAllOperations];
}
- (IBAction)suspend:(id)sender {
static int i = 0;
UIButton * btn = (UIButton *)sender;
if (i == 0) {
i = 1;
[btn setTitle:@"恢复" forState:UIControlStateNormal];
[self.quque setSuspended:YES];
}else{
i = 0;
[btn setTitle:@"暂停" forState:UIControlStateNormal];
[self.quque setSuspended:NO];
}
}
#pragma mark - 最大并发数
- (void)test6{
self.quque.maxConcurrentOperationCount = 3;
for (int i = 0; i < 20; i++) {
[self.quque addOperationWithBlock:^{
[self longtimeOperation:[NSNumber numberWithInt:i]];
}];
}
}
#pragma mark - !!!线程间通信
- (void)test5{
[self.quque addOperationWithBlock:^{
NSLog(@"1:%@", [NSThread currentThread]);
NSURL * url = [NSURL URLWithString:@"http://yuting.local/shareX/qiushi.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary * dcit = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"2:%@", [NSThread currentThread]);
NSLog(@"%@",dcit);
}];
}];
}
#pragma mark - NSOperation的基本使用
- (void)test4{
[self.quque addOperationWithBlock:^{
[self longtimeOperation:@4];
}];
}
- (void)test3{
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
[self longtimeOperation:@10];
}];
[self.quque addOperation:operation];
}
- (void)test2{
for (int i = 0; i < 10; i++) {
NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(longtimeOperation:) object:[NSNumber numberWithInt:i]];
[self.quque addOperation:operation];
}
}
- (void)test1{
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(longtimeOperation:) object:@1];
[queue addOperation:operation];
}
#pragma mark - 耗时操作
- (void)longtimeOperation:(NSNumber *)i{
sleep(3);
NSLog(@"%@%@", [NSThread currentThread], i);
}
@end