【发布时间】:2015-04-10 06:22:08
【问题描述】:
Apple 文档说“NSInvocation 不支持使用可变数量的参数或联合参数调用方法。”
我搜索了几个小时,有人说 var_list 有效,但我尝试了,它没有
但我认为可能有一种方法可以对变量参数函数做同样的事情(反射),正如我提到的,[stringWithFormat:],
所以,我找到了方法,请阅读下面的代码。
@interface INTObj : NSObject
@property (nonatomic, assign) int realvalue
@end
@interface FloatObj : NSObject
@property (nonatomic, assign) float realvalue
@end
// here ,the selectorName is only know in runtime
NSString *selectorName = @"stringWithFormat:";
SEL selector = NSSelectorFromString(selectorName);
typedef id (*Obj_Imp)(id,SEL,...);
Method md = class_getClassMethod(obj, selector); // here, obj means NSString
Obj_Imp fun = (Obj_Imp )method_getImplementation(md); // stringWithFormat:...
NSString *arg1 = @"hello %f %d";
FloatObj *fo = [[FloatObj alloc] init];
fo.realvalue = 11.3;
INTObj *io = [[INTObj alloc] init];
io.realvalue = 5;
NSObject *arr[3] = {arg1, fo,io};
// it cracks . exc_bad_Access code = 1
NSString *result = fun(obj , selector, arr[0], [arr[1] realvalue],[arr[2] realvalue]) ;
// it works but i cant do this ,because i don't know the type of the 4th parameters at Runtime
NSString *result = fun(obj , selector, arr[0],[(FloatObj *)arr[1] realvalue],[arr[2] realvalue])
为什么函数“fun”的第二次调用有效,而第一次调用失败了?
有没有更好的方法来做到这一点?
【问题讨论】:
-
1. “论点1”是什么意思?
selector?还是第一个 (arr[0]) 或第二个参数 (arr[1]) 传递给该方法? 2. 这个问题的背景是什么,你想完成什么? -
@AminNegm-Awad 感谢您的评论。我编辑了代码就知道了,对比两个名为 fun 的调用函数可以发现区别,第二个是获取类型转换 ((FloatObj *)) 。为什么第二个函数调用工作正常,但第一个不是。 arr 是一个存储对象的 C 数组,你没看到初始化吗?我想为目标 C 构建运行时反射,例如 Java 反射。
-
你没有使用 ARC 是吗?因为如果你是,你会 1) 得到一个错误
NSObject没有声明realvalue,如果你把它改成id,你会 2) 仍然得到一个错误,说多个方法realvalue不匹配类型。
标签: ios objective-c reflection objective-c-runtime nsinvocation