网络多线程-NSOperation的简单使用

来源:互联网 发布:七五事件汉人反击 知乎 编辑:程序博客网 时间:2024/05/18 03:58

import "ViewController.h"

#import "XMGOperation.h"

@interface ViewController ()


@end


@implementation ViewController


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    [selfcustomOperation];

}


-(void)customOperation

{

    NSLog(@"-----");

    //1.封装操作

    XMGOperation *op1 = [[XMGOperationalloc]init];

    XMGOperation *op2 = [[XMGOperationalloc]init];

    

    //2.启动执行

    [op1 start];

    [op2 start];

}

-(void)invocationOperation

{

    //1.封装操作

    /*

     第一个参数:目标对象SELF

     第二个参数:要调用的是哪个方法

     第三个参数:方法的参数

     */

    NSInvocationOperation *op1 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run)object:nil];

    //2.启动执行操作

    [op1 start];

    

    NSInvocationOperation *op2 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run)object:nil];

    //2.启动执行操作

    [op2 start];

    

    NSInvocationOperation *op3 = [[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run)object:nil];

    //2.启动执行操作

    [op3 start];

}


-(void)blockOperation

{

    //1.封装操作

    NSBlockOperation *op1 = [NSBlockOperationblockOperationWithBlock:^{

        //主线程

        NSLog(@"1---%@",[NSThreadcurrentThread]);

      

    }];

    NSBlockOperation *op2 = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"2---%@",[NSThreadcurrentThread]);

    }];

    

    NSBlockOperation *op3 = [NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"3---%@",[NSThreadcurrentThread]);

    }];

    

    //添加额外任务

    [op3 addExecutionBlock:^{

        //子线程

        NSLog(@"4---%@",[NSThreadcurrentThread]);

    }];

    

    [op3 addExecutionBlock:^{

        NSLog(@"5---%@",[NSThreadcurrentThread]);

    }];

    

    //2.启动执行操作

    [op1 start];

    [op2 start];

    [op3 start];

}

-(void)run

{

    NSLog(@"run---%@",[NSThreadcurrentThread]);

}



@end

0 0