美文网首页
OC 反射传参数

OC 反射传参数

作者: woniu | 来源:发表于2022-12-06 16:32 被阅读0次

    在写SDK或者组件库的时候,我们通常会遇到调用主工程的类的问题,但是由于我们组件库内部无法引入相关类,

    1、performSelector
    一般的数据用performSelector就可以传参,但是基本数据类型如int,NSInteger等都不能传参。

        Class TYTRedirectUrl = NSClassFromString(@"TYTRedirectUrl");
        [TYTRedirectUrl performSelector:@selector(popRootVCWithTabIdx:) withObject:2];
    

    2、NSInvocation
    为了解决上面的问题,我们说使用NSInvocation来处理。这里注意点[invocation setArgument:&tabIdx atIndex:2];,索引必须写2,否则就无法传参tabIdx。是最后一个索引,写3就超出索引,就会崩溃掉。

      NSInteger tabIdx = 2;
      Class class = NSClassFromString(@"NextViewController");
      SEL sel = NSSelectorFromString(@"popRootVCWithTabItem:");
      NSMethodSignature *signature = [class methodSignatureForSelector:sel];
      NSInvocation *invocation = [NSInvocation 
      invocationWithMethodSignature:signature];
      [invocation setArgument:&tabIdx atIndex:2];
      invocation.selector = sel;
      invocation.target = class;
      [invocation invoke];
    

    相关文章

      网友评论

          本文标题:OC 反射传参数

          本文链接:https://www.haomeiwen.com/subject/idlifdtx.html