zoukankan      html  css  js  c++  java
  • performSelector

    perfromSelector

    底层源码地址:https://opensource.apple.com/tarballs/objc4/

    非延迟方法

    - (id)performSelector:(SEL)sel {
        if (!sel) [self doesNotRecognizeSelector:sel];
        return ((id(*)(id, SEL))objc_msgSend)(self, sel);
    }
    
    - (id)performSelector:(SEL)sel withObject:(id)obj {
        if (!sel) [self doesNotRecognizeSelector:sel];
        return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj);
    }
    
    - (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
        if (!sel) [self doesNotRecognizeSelector:sel];
        return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2);
    }

    performSelector是运行时系统负责去找方法,在编译时不会对调用的方法做检查,只有在运行的时候才会检查,如果方法存在就调用,如果方法不存在就不会调用。当然也可以通过使用 - (BOOL)respondsToSelector:(SEL)aSelector;方法去判断对象是否实现了要调用的方法。
    这三个方法调用都是直接执行,相当于直接通过对象调用方法, [self performSelector:@selector(test)];与[self test]; 执行的结果是一致的,通过这些方法去执行是不需要子线程去启动Runloop的方法内运行的线程就是调用performSelector所在的线程
    - (void)viewDidLoad {
        [super viewDidLoad];
        NSLog(@"当前线程:%@",[NSThread currentThread]);
        [self performSelector:@selector(test1)];
        [self performSelector:@selector(test2:) withObject:@"小明"];
        [self performSelector:@selector(test3:andAge:) withObject:@"小明" withObject:@"10"];
        NSLog(@"****************************************");
        dispatch_queue_t queue = dispatch_queue_create("新的并发队列", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            NSLog(@"当前线程:%@",[NSThread currentThread]);
            [self performSelector:@selector(test1)];
            [self performSelector:@selector(test2:) withObject:@"小明"];
            [self performSelector:@selector(test3:andAge:) withObject:@"小明" withObject:@"10"];
        });
    }
    
    -(void)test1{
        NSLog(@"执行了test1 当前线程:%@",[NSThread currentThread]);
    }
    
    -(void)test2:(NSString *)name{
        NSLog(@"执行了test2 name:%@ 当前线程:%@",name,[NSThread currentThread]);
    }
    
    -(void)test3:(NSString *)name andAge:(NSString *) age{
        NSLog(@"执行了test3 name:%@ age:%@ 当前线程:%@",name,age,[NSThread currentThread]);
    }
    /*输出
     当前线程:<NSThread: 0x600000624a80>{number = 1, name = main}
     执行了test1 当前线程:<NSThread: 0x600000624a80>{number = 1, name = main}
     执行了test2 name:小明 当前线程:<NSThread: 0x600000624a80>{number = 1, name = main}
     执行了test3 name:小明 age:10 当前线程:<NSThread: 0x600000624a80>{number = 1, name = main}
     ****************************************
     当前线程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
     执行了test1 当前线程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
     执行了test2 name:小明 当前线程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
     执行了test3 name:小明 age:10 当前线程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
    上面的方法,最多可以支持传递2个参数,如果要传递2个以上,上面的方法就不能使用了。

         方法一 objc_msgSend

    ((void (*) (id, SEL, NSString *, NSString *, NSString *)) objc_msgSend) (self, @selector(test4:andAge:andSex:), @"小明", @"10", @"男");

    1. -(void)test4:(NSString *)name andAge:(NSString *) age andSex:(NSString *)sex{
          NSLog(@"执行了test4 name:%@ age:%@ sex:%@ 当前线程:%@",name,age,sex,[NSThread currentThread]);
      }
      
      /*输出
      执行了test4 name:小明 age:10 sex:男 当前线程:<NSThread: 0x600000a68580>{number = 1, name = main}
      */
    2. 方法二 NSInvocation
     //1、方法签名
      NSMethodSignature *signature = [[self class]instanceMethodSignatureForSelector:@selector(test4:andAge:andSex:)];
        //包装方法
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        //方法调用者
         invocation.target = self;
         //要调用的方法和方法签名中的方法一样
        invocation.selector = @selector(test4:andAge:andSex:);
        NSString *name = @"小明";
        NSString *age = @"10";
        NSString *sex = @"男";
        //设置传递的参数 0 代表target 1代表 selector 所以从2开始
        [invocation setArgument:&name atIndex:2];
        [invocation setArgument:&age atIndex:3];
        [invocation setArgument:&sex atIndex:4];
        //执行方法
        [invocation invoke];
        //获取返回值
        NSString *returnValue = @"";
        [invocation getReturnValue:&returnValue];
        NSLog(@"返回值:%@",returnValue);
        
        
    -(NSString *)test4:(NSString *)name andAge:(NSString *) age andSex:(NSString *)sex{
        NSLog(@"执行了test4 name:%@ age:%@ sex:%@ 当前线程:%@",name,age,sex,[NSThread currentThread]);
        return @"这是返回值";
    }
    
    /*
     执行了test4 name:小明 age:10 sex:男 当前线程:<NSThread: 0x600000f9c980>{number = 1, name = main}
      返回值:这是返回值
    */


    延迟执行方法

    - (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray<NSRunLoopMode> *)modes;
    
    - (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;

    当前线程的runloop上执行aSelector消息,这个计时器的默认模式是NSDefaultRunLoopMode。当计时器触发时,会尝试从runloop中取出消息行,如果runloop运行的模式是NSDefaultRunLoopMode,那么就会执行它,如果当前runloop是其他模式,则会等待runloop处于NSDefaultRunLoopMode在运行。

    如果希望在运行循环处于NSDefaultRunLoopMode以外的其他模式时使消息出队,请改用performSelector:withObject:afterDelay:inModes:方法。如果不确定当前线程是否为主线程,则可以使用performSelectorOnMainThread:withObject:waitUntilDone:或performSelectorOnMainThread:withObject:waitUntilDone:modes:方法来确保选择器在主线程上执行。要取消排队的消息,请使用cancelPreviousPerformRequestsWithTarget:或cancelPreviousPerformRequestsWithTarget:selector:object:方法。

    特别注意事项
    此方法向其当前上下文的runloop进行注册,并依赖于runloop才能正确执行。一种常见情况是,当在 dispatch queue上调用这个方法,但是runloop并没有启动,这个方法是不会运行的。如果想使用这个延迟功能在dispatch queue上,则应使用dispatch_after和相关方法来获得所需的行为。

    1. 在主线程中调用
    -(void)test1:(NSString *)name{
        NSLog(@"执行了test1 name:%@ 当前线程:%@",name,[NSThread currentThread]);
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //在主线程中,它的runloop是默认开启的,所有下面的方法是可以直接执行
        [self performSelector:@selector(test1:) withObject:@"小明" afterDelay:2];
    }
    
    
    //输出
    //执行了test1 name:小明 当前线程:<NSThread: 0x6000012a8b00>{number = 1, name = main}

        在队列中,不调用[[NSRunLoop currentRunLoop] run];

    - (void)viewDidLoad {
        [super viewDidLoad];
        dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            //这个方法是不会执行的,因为此时的这个线程的runloop默认是没有开启的
            [self performSelector:@selector(test1:) withObject:@"小红" afterDelay:2];
        });
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
        dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            [[NSRunLoop currentRunLoop] run];
            //这个方法是不会执行的,调用run方法只是尝试开启当前线程中的runloop,但是如果该线程中并没有任何事件(source、timer、observer)的话,runloop并不会开启。
            [self performSelector:@selector(test1:) withObject:@"小红" afterDelay:1];
        });
    }

    在队列中,在调用performSelector之后调用[[NSRunLoop currentRunLoop] run];

    -(void)viewDidLoad {
        [super viewDidLoad];
        dispatch_queue_t queue = dispatch_queue_create("并发队列", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            //成功调用函数
            [self performSelector:@selector(test1:) withObject:@"小红" afterDelay:1];
            [[NSRunLoop currentRunLoop] run];
        });
    }
    //输出
    //执行了test1 name:小红 当前线程:<NSThread: 0x6000015b0a00>{number = 7, name = (null)}
    提高技能如同提升自信心。
  • 相关阅读:
    自己实现 一个 Vue框架,包含了Vue的核心原理
    Vue-Cli 3.0 中配置高德地图的两种方式
    element-ui table 点击某行高亮(修改背景色)
    input type="file"获取文件名方法
    使用 http-proxy-middleware 做转发, post 请求转发失败
    core-js@2 core-js@3报错问题
    VUE判断当前设备是PC还是移动端
    Vue函数式组件 简单实现
    清明节哀悼日网页变黑白色的CSS代码
    Vue实现递归menu
  • 原文地址:https://www.cnblogs.com/chims-liu-touch/p/14491882.html
Copyright © 2011-2022 走看看