【问题标题】:Calling a static method in an unknown type of class在未知类型的类中调用静态方法
【发布时间】:2012-07-30 10:16:04
【问题描述】:

我有一个有趣的问题,我试图在一个类上调用类方法,而我在我的测试方法中基本上一无所知。我可以检查它的继承和它可能实现的任何协议,但看不到一种简单的方法来调用它的方法而不被 NSInvocation 束缚。下面的代码虽然很粗略,但试图证明我遇到的问题。

@interface ClassA : NSObject

+ (Class)classIsPartialClassOf;

@end

@implementation ClassA

+ (Class)classIsPartialClassOf {
    return [NSString class];
}

@end

@interface ClassB : NSObject

@end

@implementation ClassB

- (id)init {

    [ClassB testClass:[ClassA class]];

}

+ (void)testClass:(Class)classDecl {

    /* obviously if you know the type you can just call the method */
    [ClassA classIsPartialClassOf];

    /* but in my instance I do not know the type, obviously there are no classmethods to perform selector such as the fictional one below */
    [classDecl performSelector:@selector(classIsPartialClassOf)];

}

@end

获取实现的方法似乎返回实例变体,我无法让它们在静态类本身上触发。

我的选择是否仅限于调用,还是我错过了一些明显的东西,应该踢自己?

提前感谢您的帮助。

【问题讨论】:

  • 在 Obj-c 中它被称为 class 方法,而不是 static 方法。区别很重要。

标签: objective-c selector performselector


【解决方案1】:

有什么问题?你的代码

[classDecl performSelector:@selector(classIsPartialClassOf)];

应该可以。随心所欲(写起来更简单)

[classDecl classIsPartialClassOf];

类对象是对象。而类方法只是在类对象上调用的简单方法。

【讨论】:

    【解决方案2】:

    “获取实现的方法似乎返回实例变体,我无法让它们在静态类本身上触发。”

    然后使用objc_getMetaClass("ClassName") 而不是objc_getClass。类对象是对象本身并且是它们的元类的实例。如果将元类对象传递给 e. G。 class_getMethod(),一切都会好的。

    【讨论】:

    • 谢谢你的帮助,它给了我前进的方向。虽然我最终没有使用元类,但它确实消除了我大脑中查看类的阻塞_*和我之前以其他方式使用过的method_*函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2015-03-09
    • 2021-03-17
    • 2011-01-13
    • 1970-01-01
    • 2016-08-15
    相关资源
    最近更新 更多