• IOS 多线程 NSOperation GCD


    1.NSInvocationOperation 

     NSInvocationOperation * op;

        NSOperationQueue * que = [[NSOperationQueuealloc]init];

        op = [[ NSInvocationOperationalloc]initWithTarget:selfselector:@selector(run:) object:@"aaa"];

        [que addOperation:op];

        //  这里不要使用   op start,否则就会出现住线程阻塞的现象。  默认情况下,调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作。只有将operation放到一个NSOperationQueue中,才会异步执行操作。

    -(void)run:(id)data

    {

        while (![op isCancelled])

        {

            [NSThreadsleepForTimeInterval:1];

            NSLog(@"run");

        }

    }

    通过   [op cancel];   来停止线程

     

    2.

     __block NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^(){

            while ( ![op isCancelled])

            {

                [NSThread sleepForTimeInterval:0.3];

                

                NSLog(@"cccc");

            }

        }];

     

    NSOperationQueue * que = [[NSOperationQueuealloc]init];

    [que addOperation:op];

    这里也需要通过  queue来控制,使用start的话也会造成阻塞。

    这里的  op  需要使用 __block 来控制,因为在^(){}里面用到,否则不对。

     

    3.自定义 NSOperation

     

    #import <Foundation/Foundation.h>

    @interface MyOperation : NSOperation

    @end

     

    #import "MyOperation.h"

     

    @implementation MyOperation

     

    -(void)main

    {

        @autoreleasepool

        {

            while ( YES )

            {

                

                [NSThreadsleepForTimeInterval:0.3];

                

                if( [self isCancelled] )

                    break;

                

                NSLog(@"aaaaaa");

            }

        }

    }

     

    //  如何调用

    -(void)aaaa

    {

        static BOOL bFlog = NO;

        if( !bFlog )

        {

            _op = [[MyOperation alloc]init];

            NSOperationQueue * que = [[NSOperationQueuealloc]init];

            

            [que addOperation:_op];

        }

        else

        {

            [_op cancel];

        }

        bFlog = YES;

    }

     

    3.  GCD

     dispatch_async(dispatch_get_global_queue(0, 0), ^(void){

            

            

            for( NSInteger index = 0; index < 10; ++ index )

            {

                [NSThreadsleepForTimeInterval:0.3];

                

                NSLog(@"index:%d",index);

                

                dispatch_async(dispatch_get_main_queue(), ^(void){

                    

                    _label.text = [NSString stringWithFormat:@"index:%d",index];

                });

            }

     

        });

  • 相关阅读:
    Vue项目中使用Vue-Quill-Editor富文本编辑器插件
    Element-UI中的Cascader 级联选择器高度以及位置问题
    Sublime中同一个文件进行分屏显示
    Oracle的clob数据类型
    查看Nginx版本号的几种方式
    华为路由器EasyNAT&NAT Server
    huawei路由器NAT配置
    15
    14
    13
  • 原文地址:https://www.cnblogs.com/rollrock/p/3546490.html
Copyright © 2020-2023  润新知