Using the Objective-C runtime, I can get a list of all of the @objc
protocols an object conforms to:
使用Objective-C运行时,我可以获得一个对象符合的所有@objc协议的列表:
let obj = NSObject()
var pc: UInt32 = 0
let plist = class_copyProtocolList(object_getClass(obj), &pc)
print("\(obj.dynamicType) conforms to \(pc) protocols")
for i in 0 ..< Int(pc) {
print(String(format: "Protocol #%d: %s", arguments: [i, protocol_getName(plist[i])]))
}
or all of the Objective-C protocols loaded by the runtime:
或者运行时加载的所有Objective-C协议:
var allProtocolCount: UInt32 = 0
let protocols = objc_copyProtocolList(&allProtocolCount)
print("\(allProtocolCount) total protocols")
for i in 0 ..< Int(allProtocolCount) {
print(String(format: "Protocol #%d: %s", arguments: [i, protocol_getName(protocols[i])]))
}
But neither of these list any Swift protocols:
但这些都没有列出任何Swift协议:
func == (lhs: MyClass, rhs: MyClass) -> Bool {
return lhs.value == rhs.value
}
class MyClass: Equatable, Hashable {
var value: Int
var hashValue: Int {
return value
}
init(value: Int) {
self.value = value
}
}
var count: UInt32 = 0;
let strProtocols = class_copyProtocolList(MyClass.self, &count) // 0x0000000000000000
strProtocols
is 0 when I would expect it to return sizeof(Protocol) * 2
(since MyClass
conforms to Equatable
and Hashable
).
strProtocols是0,当我希望它返回sizeof(协议)* 2(因为MyClass符合Equatable和Hashable)。
Is there an interface exposed by the runtime to get a list of protocols an object conforms to?
是否有运行时公开的接口来获取对象符合的协议列表?
1 个解决方案
#1
4
You can't. Swift protocols that are not ObjC ones only exist at compile time and do not really exist on the object itself (which is why their methods are dispatched statically based on the type of the variable).
你不能。不是ObjC的Swift协议只存在于编译时,并且实际上并不存在于对象本身上(这就是为什么它们的方法是根据变量的类型静态调度的)。
#1
4
You can't. Swift protocols that are not ObjC ones only exist at compile time and do not really exist on the object itself (which is why their methods are dispatched statically based on the type of the variable).
你不能。不是ObjC的Swift协议只存在于编译时,并且实际上并不存在于对象本身上(这就是为什么它们的方法是根据变量的类型静态调度的)。