ios - 如何从 Swift 中的实例访问 Objective-C 类方法

标签 ios

如果有这样的 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/

相关文章:

ios - 避免在 UITableView iOS 的 beginUpdates 上重新加载内容

ios - 从方法内部获取函数数据(包括简单代码)

ios - 如何仅将 UIView 的部分 subview 转换为 UIImage

用于注册客户以保留购买信息的 ios 唯一编号

ios - iOS:提前3天发送简单本地通知

ios - 什么可以是用户帐户的唯一标识符?

ios - 如果我将 UUID 存储在钥匙串(keychain)中,iOS 应用商店批准是否有任何问题

iOS App Today Widget App Group Entitlement with Keychain Sharing Entitlement,设备错误如模拟器 -25243 (errSecNoAccessForItem)

ios - 如何以编程方式快速更改应用程序的 Localizable 字符串文件?

ios - 应用程序删除锁 - swift