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]);

    }

  • 相关阅读:
    leetcode 264: Ugly Number II
    leetcode 260: Single Number III
    leetcode 241: Different Ways to Add Parentheses
    清远市技术学院大学城网
    英德市职业技术学校大学城网
    清远市田家炳中学大学城网
    清远市清城区清城中学大学城网
    清远市第一中学大学城网
    当前最热的技术
    Python 学习视频
  • 原文地址:https://www.cnblogs.com/PJXWang/p/5950138.html
Copyright © 2011-2022 走看看