关于 NSInvocation

Invocation   调用的意思。

可想而知NSInvocation 是一个 方法调用 封装的类。

这体现了  面向对象的思想, 及一切皆对象。函数也不例外。

一般编程中,应该很少用到这个。 但是要编写 抽象度高的 框架,或 代码。 这个是必不可少的。

跟 c# , java 里的 反射 类似 。 动态访问 和 调用方法。

下面介绍下简单使用。。

 

用之前可以先 自己想下。如果让你 来 封装一个函数 作为一个类 ,都需要什么。

funObj  函数 对象

funObj 属性 

funObj 行为(方法fun)

首先属性,需要 函数的一个描述:

{

 1,唯一标示 一个函数

 2,函数 在 程序里的 调用指针。

}

函数的参数:

{

arg 1

arg 2

}

函数的返回值:

{

returnValue

}

函数的调用对象

{

要调用方法的外部对象。

}

其次   函数对象的行为(fun)

{

有了足够多的信息后,我们就可以 拿到 外部调用对象 去 内存里找 函数的调用地址, 加上函数参数、返回值。 来调用函数。

}

 

以上这些,在面向对象的语言里 可能已经为我们封装了,OC 中的NSInvocation 就是。

对于调用一个 有两个参数以上的   函数,我们可以这样:

-( id )fun :(id) a :(id)b ......{

}

[self    fun:a : b .....]; //很简单啊。这是在确定的情况下。不确定呢,

使用

[self performSelector:@selector() withObject: .....];

很遗憾 只能传递一个参数, 除非你把 a,b 参数放倒一个 集合中。

使用NSInvocation
-(NSString *)customMethod:(NSString *)arg1 otherArg:(NSString *)arg2{
    
    return [NSString stringWithFormat:@"%@%@",arg1,arg2];
    
}


    SEL customSel = @selector(customMethod: otherArg:);
    
    NSMethodSignature * customSig = [self methodSignatureForSelector:customSel];
    
    NSInvocation *customInvocation =  [NSInvocation  invocationWithMethodSignature:customSig ];
    NSString *arg1 = @"NS";
    NSString *arg2 = @"Invocation";

    [customInvocation setTarget:self];
    [customInvocation setReturnValue:@encode(NSString)];
    
    [customInvocation setSelector:customSel];
    [customInvocation setArgument:&arg1 atIndex:2];
    [customInvocation setArgument:&arg2 atIndex:3];

    [customInvocation invoke];

 

    SEL customSel = @selector(customMethod: otherArg:); 

 

 

posted @ 2014-10-19 15:48  hhhker  阅读(503)  评论(0编辑  收藏  举报