代码demo
已在Github
开源, MXRuntimeUtils, 若是能帮助到您,请帮忙点个星star哈,谢谢!html
MXRuntimeUtils 是用于替换 -[NSObject performSelector:object:object:]的工具,很是容易使用!git
若是你想使用如下方法github
- (id)testMethodWithIntValue:(int)aIntValue floatValue:(float)aFloatValue charValue:(char)aCharValue sizeValue:(CGSize)aCGSizeValue pointValue:(CGPoint)aCGPointValue edgeInsetsValue:(UIEdgeInsets)anUIEdgeInsetsValue stringValue:(NSString *)aStringValue idValue:(id)anIdValue {
return @[@(aIntValue), @(aFloatValue), @(aCharValue), [NSValue valueWithCGSize:aCGSizeValue], [NSValue valueWithCGPoint:aCGPointValue], [NSValue valueWithUIEdgeInsets:anUIEdgeInsetsValue], aStringValue, anIdValue];
}
复制代码
并且你想调用 -[self testMethodWithIntValue:floatValue:charValue:sizeValue:pointValue: edgeInsetsValue: stringValue:idValue:]
可是用另外一种方式来表达 -[self performSelector:object:object:]
, 你可能感到懵逼, 由于 -[NSObject performSelector:withObject:withObject:]]
最高仅仅容许传两个值,并且还只能是id类型,那么,你怎么传基本数据类型,好比像 BOOL, char, int, float ,甚至超过两个参数的上限呢!工具
//[self performSelector:@selector(testMethodWithIntValue:floatValue:charValue:sizeValue:pointValue:edgeInsetsValue:stringValue:idValue:) withObject:one withObject:two ....];
复制代码
仅仅一行代码spa
[MXRuntimeUtils callMethodWithTarget:self selector:@selector(testMethodWithIntValue:floatValue:charValue:
sizeValue:pointValue:edgeInsetsValue:stringValue:idValue:) argumemts:@[@1, @2.0f, [NSNumber numberWithChar:'3'], [NSValue valueWithCGSize:CGSizeMake(4, 4)],
[NSValue valueWithCGPoint:CGPointMake(5, 5)], [NSValue valueWithUIEdgeInsets:UIEdgeInsetsMake(6, 6, 6, 6)], @"7", @"8"] returnValue:&returnValue];
复制代码
若是你的原始方法有一个返回值,那么就传一个返回值类型的指针,就像这样,若是你的返回值是一个OC对象, 注意要传一个 __autoreleasing 变量就像 这样 __autoreleasing NSString stringReturnValue, __autoreleasing id idReturnValue 而不是***NSString stringReturnValue, id idReturnValue*, 理由你能够看看这篇文章 memory management指针
//int returnValue
int sumReturnValue = 0;
[MXRuntimeUtils callMethodWithTarget:self selector:@selector(sumWithAnIntValue:anotherIntValue) argumemts:@[@1, @2] returnValue:&returnValue];
//sumReturnValue = 3;
//id returnValue
__autoreleasing id idReturnValue = nil;//avoid idReturnValue is dealloc after method invoking
[MXRuntimeUtils callMethodWithTarget:self selector:@selector(ConvertIntValueToIdType:) argumemts:@[@1] returnValue:&idReturnValue];
//idReturnValue = @1;
复制代码
以后你就能够从sumReturnValue
中获得数字3
, idReturnValue中获得1
code
示例代码中的demo
截图就像这样, 可是你会有点疑惑,为何我传的值是字符类型char 3
,转换成数字类型咋变成了51
了,事实上, 在 ASCII
中 char value '3'
就是 数字 51
, 就像 'A'
是 65
, 'a' 是 97
同样 orm
若是你传一个 CGPoint
类型的值给一个 声明为int类型的方法参数,断言会触发,你会在Xcode控制台
中获得如下截图信息cdn
容许传两个以上的参数htm
获得任何类型的返回值