动态调用Objective C中的类方法

Gre*_*egK 41 cocoa cocoa-touch objective-c

假设我有Objective C接口SomeClass,它有一个叫做的类方法someMethod:

@interface SomeClass : NSObject {
}

+ (id)someMethod;
@end
Run Code Online (Sandbox Code Playgroud)

在其他一些接口中,我希望有一个辅助方法,可以someMethod像这样在类上动态调用:

[someOtherObject invokeSelector:@selector(someMethod) forClass:[SomeClass class];
Run Code Online (Sandbox Code Playgroud)

应该实施invokeSelector什么?有可能吗?

- (void)invokeSelector:(SEL)aSelector forClass:(Class)aClass {
   // ???
}
Run Code Online (Sandbox Code Playgroud)

ste*_*anB 83

代替:

[someOtherObject invokeSelector:@selector(someMethod) forClass:[SomeClass class];
Run Code Online (Sandbox Code Playgroud)

呼叫:

[[SomeClass class] performSelector:@selector(someMethod)];
Run Code Online (Sandbox Code Playgroud)

示例(使用GNUstep ...)

文件啊

#import <Foundation/Foundation.h>
@interface A : NSObject {}

- (NSString *)description;
+ (NSString *)action;
@end
Run Code Online (Sandbox Code Playgroud)

文件Am

#import <Foundation/Foundation.h>
#import "A.h"

@implementation A

- (NSString *)description
{
    return [NSString stringWithString: @"A"];
}

+ (NSString *)action
{
    return [NSString stringWithString:@"A::action"];
}

@end
Run Code Online (Sandbox Code Playgroud)

别的地方:

A *a = [[A class] performSelector:@selector(action)];
NSLog(@"%@",a);
Run Code Online (Sandbox Code Playgroud)

输出:

2009-11-22 23:32:41.974 abc[3200] A::action
Run Code Online (Sandbox Code Playgroud)

很好的解释来自http://www.cocoabuilder.com/archive/cocoa/197631-how-do-classes-respond-to-performselector.html:

"在Objective-C中,类对象获取其层次结构的根类的所有实例方法.这意味着从NSObject下降的每个类对象都获取所有NSObject的实例方法 - 包括performSelector:."

  • Code Sense不建议`[SomeClass class]`experssion的`performSelector`. (10认同)