zoukankan      html  css  js  c++  java
  • ios开发-NSOperation介绍

    简介:

    1、NSOperation是苹果对GCD的一个面向对象的封装,是OC的

    2、NSOperation同时提供了一些GCD不是特别容易实现的功能

    3、将操作添加到队列,操作会被立即”异步“执行

    4、NSOperation是个抽象的类,并不具备封装操作的能力,必须使用它的子类

       1>NSInvocationOperation

      2>NSBlockOperation

      3>自定义类继承NSOperation,实现内部的方法

    代码实现:

    示例1:NSInvocationOperation

    @interface TBViewController ()

    @property(nonatomic,strong)NSOperation *myQueue;

    @end

    //懒加载

    -(NSOperationQueue *)myQueue

    {

      if(_myQueue == nil){

      _myQueue =[ [NSOperationQueue alloc]init];

    }

      return _myQueue;

    }

      -(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

    {

      [self opDemo1];

    }

    -(void)opDemo1

    {

      //操作

      NSInvocationOperation *op =[ [NSInvocationOperation alloc]initWithTarget:self selector:@selector(downLoadImage) object:nil];

      //让操作启动,如果使用start方法,会在当前线程执行操作

     // [op start];

      //将操作添加到队列,操作会立即被“异步”执行

      [self.myQueue addOperation:op];

    }

    //下载图像

    -(void)downLoadImage

    {

      NSLog(@"下载图像:%@",[NSThread currentThread]);

    }

    示例2:NSBlockOperation

    //NSOperationQueue  实例化的对象是并发队列

    -(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

    {

      [self opDemo1];

    }

    -(void)opDemo2

    {

      //操作

      for(int i = 0;i < 10; i ++)

    {

      NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"block ===%@",[NSThread currentThread]);

    }];

      //添加到队列  通过运行可以看到是”并发“队列

      [self.myQueue addOperation:op];

    }  

    }

    示例3:直接添加block

    -(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

    {

      [self opDemo3];

    }

    -(void)opDemo3

    {

       for(int i = 0; i < 10; i++)

    {

      [self .myQueue addOperationWithBlock:^{

      NSLog(@"===== %@",[NSThread currentThread]);

    }];

    }

    }

    示例4:线程间的通讯

    -(void)touchesBegan:(NSSer *)touches withEvent:(UIEvent *)event

    {

      [self opDemo4];

    }

    -(void)opDemo4

    {

      [self.myQueue addOperationWithBlock:^{

      NSLog(@"下载图像:%@",[NSThread currentThread]);

      //下载完成需要更新UI,mainQueue  主队列

      [[NSOperationQueue mainQueue] addOperationWithBlock:^{

      NSLog(@"main %@",[NSThread currentThread]);

    }];

    }];

    }

  • 相关阅读:
    XML节点处理
    Log4Net使用记录
    WPF选择文件夹及文件操作
    SQL 一些语句记录
    一篇MSSQL事务的测试文章
    游标示例
    WPF实现多线程加载数据
    MS SQL索引学习
    Entity Framework 利用 Database.SqlQuery<T> 执行存储过程,并返回Output参数值
    手持移动端特殊链接:打电话,发短信,发邮件
  • 原文地址:https://www.cnblogs.com/gtbo/p/4039121.html
Copyright © 2011-2022 走看看