如果有这样的 Objective-C 代码:
@protocol MyProtocol
@required
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
@interface MyClass <MyProtocol>
@end
@implementation MyClass
+(void)aClassMethod {
}
-(void)anInstanceMethod {
}
@end
并且只有以下内容在 Swift 中可用:
func myFunc(obj: MyProtocol) {
// want to access aClassMethod here
}
那么我如何访问obj
上的aClassMethod
?
--编辑--
对我想要实现的目标进行一些澄清。让我们加入另一个类:
@interface AnotherClass <MyProtocol>
@end
@implementation AnotherClass
+(void)aClassMethod {
// Here I'm doing something different than in MyClass
}
-(void)anInstanceMethod {
}
@end
然后在 Swift 中,如果我有这个:
let a = MyClass()
let b = AnotherClass()
myFunc(a)
myFunc(b)
我希望 myFunc
能够在其接收的对象上调用 aClassMethod
。
原因:我正在创建类作为存储数据的模型。每个模型类都有一个字符串名称,每个实例的名称都是相同的,因此类方法也是如此。我传递这些实例,但我希望将它们的名称放入 URL 中。
最佳答案
您正试图从同一类的实例调用类方法,这是不可能的。相反,您可以调用 MyClass.aClassMethod()
或 obj.anInstanceMethod()
。
MyClass() acts as an initializer. When using it, you're creating a new instance of your class on which you can only use instance methods.
关于ios - 如何从 Swift 中的实例访问 Objective-C 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30299874/