如何通过反射传入基本数据类型参数

2023-06-13  本文已影响0人  咚咚嗒大人

如何通过反射传入基本数据类型参数?

- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
NSNumber *appID = @(100);
Class class = NSClassFromString(@"xxx");
[class performSelector:NSSelectorFromString(@"类方法") withObject:appID];

直接使用上面的performSelector的方式是走不通的,可以使用NSInvocation。

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//checkInputValueEqual:withError:  验证两次输入内容是否一致
            SEL mysel = NSSelectorFromString(@"checkInputValueEqual:withError:");
            if ([codeView2 respondsToSelector:mysel]) {
                NSInteger comparErrorCode = 0;
//                1、方法签名
                NSMethodSignature* signature = [codeView2 methodSignatureForSelector:mysel];
                const char* retType = [signature methodReturnType];
                if (strcmp(retType, @encode(BOOL)) == 0) {
                    //包装方法
                    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
                    //方法调用者
                    invocation.target = codeView2;
                        //要调用的方法和方法签名中的方法一样
                    invocation.selector = mysel;
                    //设置传递的参数 0 代表target 1代表 selector 所以从2开始
                    [invocation setArgument:&firstTextField atIndex:2];
                    [invocation setArgument:&comparErrorCode atIndex:3];
                    //执行方法
                    [invocation invoke];
                    //获取返回值
                    BOOL result = 0;
                    [invocation getReturnValue:&result];
                    
                    if (result) {
                        if (weakself.closeBlock) {
                            weakself.closeBlock(encryptedData2, clientRandomEncryptedData2,weakself.param.strServerRandom2);
                        }
                    }else {
                        [weakself reloadCodeView:@"密码输入不一致,请重新输入!"];
                    }
                }
            }
#pragma clang diagnostic pop
上一篇下一篇

猜你喜欢

热点阅读