[英]How to access an Objective-C class method from an instance in Swift
如果有這樣的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()充當初始化程序。 使用它時,您正在創建類的新實例,在該實例上只能使用實例方法。
得到它了!
func myFunc(obj: MyProtocol) {
object_getClass(obj).aClassMethod()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.