zoukankan      html  css  js  c++  java
  • NSOperation使用的三种方法

    //1.invacationOperation

    注意:在默认情况下,调用start方法后,并不会开启一条新的线程去执行操作,而是在当前线程同步执行操作;只有将NSOperation放到NSOperationQueue中,才会异步执行操作

    -(void)invocationOperation

    {

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

        [ip start];

    //    [self performSelector:@selector(operation) withObject:nil];

    }

    //2.blockOperation

    注意:只要NSBlockOperation封装的操作数大于1,就会开启新线程,异步执行

    -(void)blockOperation

    {

        NSBlockOperation *bp = [NSBlockOperation blockOperationWithBlock:^{

    //在主线程中完成

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

        }];

    //额外任务在子线程完成

        [bp addExecutionBlock:^{

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

        }];

        [bp start];

        

    //3.自定义PJXCustomOperation继承NSOperation

    #import <Foundation/Foundation.h>

    @interface PJXCustomOperation : NSOperation

    @end

    #import "PJXCustomOperation.h"

    @implementation PJXCustomOperation

    //在实现文件中实现-main方法

    -(void)main

    {

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

    }

    //自定义

    -(void)customOperation

    {

        PJXCustomOperation *cp = [[PJXCustomOperation alloc]init];

    }

    }

    -(void)operation

    {

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

    }

    4.NSOperationQueue:

    1)作用:如果将NSOperation添加到NSOperationQueue中,系统会异步执行NSOperation操作

    2)添加:

    方法一:调用addOperation:的方法

    方法二:调用addOperationWithBlock:的方法

    5.NSOperationQueue与GCD

    GCD队列形式:1)全局 2)主队列 3)串行(自己创建的) 4)并行队列(自己创建)

    NSOperationQueue队列形式:1)主队列 2)自己创建的

      NSOperationQueue *operationQueue = [[NSOperationQueue alloc ]init];

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

    //    [operationQueue addOperation:op];

        [operationQueue addOperationWithBlock:^{

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

        }];

    -(void)operation{

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

    }

  • 相关阅读:
    php date 时间差
    array_merge 和 + 号的的区别
    apache 添加https后导致http无法访问
    php 获取url
    TP5 事务处理
    LeetCode 每日一题 (盛最多水的容器)
    LeetCode 每日一题 (字符串转换整数 (atoi))
    LeetCode 每日一题(5. 最长回文子串)
    LeetCode 每日一题 (3 无重复字符的最长子串)
    LeetCode 每日一题 (两数相加)
  • 原文地址:https://www.cnblogs.com/PJXWang/p/5950138.html
Copyright © 2011-2022 走看看