Objective-C 中的后代枚举
是否有可能获得 Objective-C 中特定类的所有后代类的列表?
就像是:
@interface A : NSObject
@end
@interface B : A
@end
@interface C : A
@end
NSArray *descendants = [A allDescendants]; // descendants = [B, C]
Is it possible to get a list of all descendant classes of a particular class in objective-c?
Something like:
@interface A : NSObject
@end
@interface B : A
@end
@interface C : A
@end
NSArray *descendants = [A allDescendants]; // descendants = [B, C]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能想到的唯一方法是枚举运行时中的整个类列表(使用 objc_getClassList 获得)并测试每个类的 isKindOfClass:A 。
这可能是唯一的解决方案,因为类不维护与其后代的链接(仅与其超类)。
The only way I can think is to enumerate the entire list of classes in the runtime (obtained with
objc_getClassList
) and test each one forisKindOfClass:A
.This is likely the only solution because classes do not maintain links to their descendants (only to their superclass).
作为示例,我链接到 解决方案 by Ken Ferry 到 Wil Shipley 博客文章。
本质上就是走课。
As an example I am linking to solution by Ken Ferry to a Wil Shipley blog post.
Essentially, walking the classes.
你能以某种方式使用班级成员吗? 调用
[[A class] superclass]
返回自身超类的Class
类的实例。 我认为您可以从类的Class
中获取类的名称 - 这会达到您想要的效果吗?这根本不真正处理协议,但也许这至少会为您指明正确的方向。
Could you use the class member somehow? Calling
[[A class] superclass]
returns an instance of theClass
class for self's superclass. I think that you can get the name of a class from itsClass
- would that do what you want?This doesn't really handle Protocols at all, but maybe this will point you in the right direction at least.