如何通过NSInvocation调用类方法?

时间:2012-06-05 15:40:04

标签: objective-c

我们可以NSMethodSignature + (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector获得NSObject。然后按NSInvocation

构建+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)signature

这是问题所在。我们只能得到实例的方法签名,类方法怎么样?

1 个答案:

答案 0 :(得分:3)

以下是有关通过显示methodForSignature:instanceMethodForSignature:

的NSInvocation调用类(和实例方法)的其他详细信息
@interface SomeObject : NSObject
+ (void)instanceAndClass;
- (void)instanceAndClass;
+ (void)classOnly;
- (void)instanceOnly;
@end

@implementation SomeObject
+ (void)instanceAndClass { NSLog(@"Class version"); }
- (void)instanceAndClass { NSLog(@"Instance version"); }    
+ (void)classOnly { NSLog(@"Class only"); }
- (void)instanceOnly { NSLog(@"Instance only"); }
@end

@implementation Foo

- (void)invoke:(id)receiver signature:(NSMethodSignature *)signature selector:(SEL)selector {
    if (!signature) {
        NSLog(@"method signature is nil");
        return;
    }        
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.selector = selector;
    invocation.target = receiver;
    [invocation invoke];
}

- (void)foo {
    NSMethodSignature *signature;
    SomeObject *someObject = [SomeObject new];

    signature = [someObject methodSignatureForSelector:@selector(instanceAndClass)];
    [self invoke:someObject signature:signature selector:@selector(instanceAndClass)];
    // 2015-07-10 11:01:10.227 FooBar[65312:3097866] Instance version
    [self invoke:[someObject class] signature:signature selector:@selector(instanceAndClass)];
    // 2015-07-10 11:01:10.227 FooBar[65312:3097866] Class version

    signature = [someObject methodSignatureForSelector:@selector(classOnly)];
    [self invoke:someObject signature:signature selector:@selector(classOnly)];
    // 2015-07-10 11:01:10.227 FooBar[65312:3097866] method signature is nil

    signature = [[someObject class] methodSignatureForSelector:@selector(classOnly)];
    [self invoke:[someObject class] signature:signature selector:@selector(classOnly)];
    // 2015-07-10 11:01:10.228 FooBar[65312:3097866] Class only

    signature = [someObject methodSignatureForSelector:@selector(instanceOnly)];
    [self invoke:someObject signature:signature selector:@selector(instanceOnly)];
    // 2015-07-10 11:01:10.228 FooBar[65312:3097866] Instance only

    signature = [[someObject class] methodSignatureForSelector:@selector(instanceOnly)];
    [self invoke:[someObject class] signature:signature selector:@selector(instanceOnly)];
    2015-07-10 11:01:10.228 FooBar[65312:3097866] method signature is nil

    signature = [[someObject class] instanceMethodSignatureForSelector:@selector(instanceOnly)];
    [self invoke:someObject signature:signature selector:@selector(instanceOnly)];
    // 2015-07-10 11:01:10.228 FooBar[65312:3097866] Instance only
}