NSMethodSignature和NSInvocation的用法

NSMethodSignature顾名思义应该就是“方法签名”,类似于C++中的编译器时的函数签名。
官方定义该类为对方法的参数、返回类似进行封装,协同NSInvocation实现消息转发。
通过消息转发可以用B实现A的方法。也是一种多重继承的解决方法。
 

在 iOS中可以直接调用 某个对象的消息 方式有2种

一种是performSelector:withObject:

再一种就是NSInvocation

第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作

NSInvocation可以处理参数、返回值。会java的人都知道反射操作,其实NSInvocation就相当于反射操作。

使用一:通过下例得到myName长度
interface LOCBird : NSObject
{
NSString* myName;
}
@end
@implementation LOCBird
- (id)init
{
self = [super init];
if (self)
{
myName = @"I am a Bird!!"];
}
return self;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];
if (signature==nil)
{
signature = [myName methodSignatureForSelector:aSelector];
}
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
NSLog(@"forwardInvocation:%@" , anInvocation);
SEL seletor = [anInvocation selector];
if ([myName respondsToSelector:seletor])
{
[anInvocation invokeWithTarget:myName];
}
}
@end
 

//调用

id bird = [[LOCBird alloc] init];

NSLog(@"len= %d", [bird length]);//  len= 13

 

使用二:定时调用

SEL selector = @selector(myMethod:withParam2:);

    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];

    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

    [invocation setSelector:selector];

    NSString *str1 = @"someString";

    NSString *str2 = @"someOtherString";

    //The invocation object must retain its arguments

    //Set the arguments

    [invocation setTarget:self];

    [invocation setArgument:&str1 atIndex:2];//参数位置 atIndex的下标必须从2开始。原因为:0 1 两个参数已经被target 和selector占用

    [invocation setArgument:&str2 atIndex:3];

    [NSTimer scheduledTimerWithTimeInterval:3.0 invocation:invocation repeats:YES];

 

-(NSString *)myMethod:(NSString *)param1 withParam2:(NSNumber *)param2

{

    NSString *result = @"objc";

 

    NSLog(@"par = %@",param1);

 

    NSLog(@"par 2 = %@",param2);

 

    return result;

}

每3秒输出:

par = someString

par 2 = someOtherString

总结:没感觉到有实质的用途,仅做了解之用

posted @ 2015-01-05 15:57  燕羽天空  Views(823)  Comments(0Edit  收藏  举报